Skip to content

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

feat(amsp,server,web,cli): 外部程序可以经 Agent API 与某个 Agent 对话

lmliheng06568c9ba4c3
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index c806a6b1..1e397b1b 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -129,6 +129,7 @@ single data directory (`~/.penguin/data`) and a single message protocol (OmniMes
| [`packages/core`](../packages/core) | `@lmliheng/penguin-core` | SDK & engine: ReAct loop, OmniMessage protocol, LLM/Environment interface contracts, Agent State, Trace |
| [`packages/cli`](../packages/cli) | `@lmliheng/penguin-cli` | The `penguin` command: REPL, one-shot runs, model & vault config, service launcher |
| [`packages/server`](../packages/server) | `@lmliheng/penguin-server` | Web backend: HTTP API + SSE streaming, multi-user auth, Project authorization, usage stats |
+| [`packages/amsp`](../packages/amsp) | `@lmliheng/amsp` | AMSP, the Agent API's event stream: its wire types, which the server imports, and a zero-dependency client for Node and browsers |
| [`packages/web`](../packages/web) | `@lmliheng/penguin-web` | Web App: multi-session chat, Agent/skill/model management, Trace observability, evaluation center |
| [`plugins/*`](../plugins) | `@lmliheng/<name>` | The built-in plugins, one npm package each: skills (software development, model development, agent development/tuning, …) and session hooks (goal mode, skill summaries); the loader lives in `packages/core` |
| [`packages/docs`](../packages/docs) | — | Documentation site (bilingual, deployed under `/docs/`) |
diff --git a/.github/CONTRIBUTING.zh.md b/.github/CONTRIBUTING.zh.md
index d735b714..ae978c72 100644
--- a/.github/CONTRIBUTING.zh.md
+++ b/.github/CONTRIBUTING.zh.md
@@ -89,6 +89,7 @@ userData 目录随其名称一并搬家,Chromium 配置文件也跟着走,
| [`packages/core`](../packages/core) | `@lmliheng/penguin-core` | SDK 与引擎:ReAct 循环、OmniMessage 协议、LLM/Environment 接口契约、Agent State、Trace |
| [`packages/cli`](../packages/cli) | `@lmliheng/penguin-cli` | `penguin` 命令:REPL、单次运行、模型与 vault 配置、服务启动器 |
| [`packages/server`](../packages/server) | `@lmliheng/penguin-server` | Web 后端:HTTP API + SSE 流式传输、多用户认证、Project 鉴权、用量统计 |
+| [`packages/amsp`](../packages/amsp) | `@lmliheng/amsp` | AMSP(Agent API 的事件流):传输类型(服务器也引用)和零依赖的客户端,适用于 Node 与浏览器 |
| [`packages/web`](../packages/web) | `@lmliheng/penguin-web` | Web App:多会话聊天,Agent/Skill/模型管理,Trace 可观测性,评测中心 |
| [`plugins/*`](../plugins) | `@lmliheng/<name>` | 内置插件,一插件一 npm 包:Skill(软件开发、模型开发、Agent 开发/调优……)与会话钩子(目标模式、技能沉淀);loader 在 `packages/core` |
| [`packages/docs`](../packages/docs) | — | 文档站(双语,部署在 `/docs/` 下) |
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index c33b8c27..999c96ca 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -95,12 +95,12 @@ jobs:
# release.yml does, so the dry run lists the real tarball.
- name: Stage what the release stages
run: |
- for p in core server cli; do cp LICENSE "packages/$p/LICENSE"; done
+ for p in amsp core server cli; do cp LICENSE "packages/$p/LICENSE"; done
rm -rf packages/server/web-dist
cp -r packages/web/dist packages/server/web-dist
- name: Pack the publishable packages
run: |
- for p in core server cli; do
+ for p in amsp core server cli; do
echo "--- packages/$p"
(cd "packages/$p" && npm pack --dry-run)
done
@@ -160,7 +160,7 @@ jobs:
pnpm --filter @lmliheng/penguin-web --filter @lmliheng/penguin-ui
--filter @lmliheng/penguin-cli test
- shard: rest
- build: "@lmliheng/penguin-desktop...,@lmliheng/penguin-cli..."
+ build: "@lmliheng/penguin-desktop...,@lmliheng/penguin-cli...,@lmliheng/amsp..."
tests: >-
pnpm -r --filter '!@lmliheng/penguin-core' --filter '!@lmliheng/penguin-server'
--filter '!@lmliheng/penguin-web' --filter '!@lmliheng/penguin-ui'
@@ -229,7 +229,7 @@ jobs:
tests: pnpm --filter @lmliheng/penguin-server test
smoke: false
- shard: rest
- build: "@lmliheng/penguin-desktop...,@lmliheng/penguin-cli..."
+ build: "@lmliheng/penguin-desktop...,@lmliheng/penguin-cli...,@lmliheng/amsp..."
tests: >-
pnpm -r --filter '!@lmliheng/penguin-core' --filter '!@lmliheng/penguin-server' test
smoke: true
@@ -290,7 +290,7 @@ jobs:
build: "@lmliheng/penguin-server..."
tests: pnpm --filter @lmliheng/penguin-server exec vitest run --shard=3/3
- shard: rest
- build: "@lmliheng/penguin-desktop...,@lmliheng/penguin-cli..."
+ build: "@lmliheng/penguin-desktop...,@lmliheng/penguin-cli...,@lmliheng/amsp..."
tests: >-
pnpm -r --filter '!@lmliheng/penguin-core' --filter '!@lmliheng/penguin-server' test
# ADELIE_MUST_RUN, as on ubuntu and macOS: the DSH live suite must run here
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 0899e3d5..200df7c7 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -16,8 +16,9 @@
# one version per tag, multiple versions coexist. Releases up to v0.1.5 shipped raw program
# archives under the same names plus *-offline wrappers; the installers keep accepting that
# legacy layout for pinned versions.
-# - publish-npm: publish the whole chain (the @lmliheng/* plugin packages -> @lmliheng/penguin-core
-# -> @lmliheng/penguin-server -> @lmliheng/penguin-cli) to npm at the tag version.
+# - publish-npm: publish the whole chain (the @lmliheng/* plugin packages -> @lmliheng/amsp
+# -> @lmliheng/penguin-core -> @lmliheng/penguin-server -> @lmliheng/penguin-cli) to npm at the
+# tag version.
# core serves the penguin-sdk Skill's `npm install`; server ships the built web assets inside
# the package (web-dist/, its default web dir falls back to it), so `npm install -g
# @lmliheng/penguin-cli` alone yields a working `penguin` incl. the Web UI (needs Node >= 24).
@@ -608,6 +609,7 @@ jobs:
for dir in plugins/*/; do
(cd "$dir" && npm version --no-git-tag-version --allow-same-version "$V")
done
+ (cd packages/amsp && npm version --no-git-tag-version --allow-same-version "$V")
(cd packages/core && npm version --no-git-tag-version --allow-same-version "$V")
(cd packages/server && npm version --no-git-tag-version --allow-same-version "$V")
(cd packages/cli && npm version --no-git-tag-version --allow-same-version "$V")
@@ -621,6 +623,7 @@ jobs:
- name: Build and test
run: |
pnpm -r build
+ pnpm --filter @lmliheng/amsp test
pnpm --filter @lmliheng/penguin-core test
pnpm --filter @lmliheng/penguin-server test
pnpm --filter @lmliheng/penguin-cli test
@@ -644,6 +647,7 @@ jobs:
run: |
TAG="${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref_name }}"
V="${TAG#v}"
+ cp LICENSE packages/amsp/LICENSE
cp LICENSE packages/core/LICENSE
cp LICENSE packages/server/LICENSE
cp LICENSE packages/cli/LICENSE
@@ -671,8 +675,9 @@ jobs:
fi
pnpm --filter "$name" publish --access public --no-git-checks
done
- for pkg in core server cli; do
- name="@lmliheng/penguin-$pkg"
+ # Full names, in dependency order: @lmliheng/amsp is not a penguin-* name, and the
+ # server depends on it, so it goes first.
+ for name in @lmliheng/amsp @lmliheng/penguin-core @lmliheng/penguin-server @lmliheng/penguin-cli; do
if [ -n "$(npm view "$name@$V" version 2>/dev/null || true)" ]; then
echo "$name@$V already on the registry, skipping."
continue
diff --git a/changelog/unreleased/2026-10-16-agent-api-amsp.md b/changelog/unreleased/2026-10-16-agent-api-amsp.md
new file mode 100644
index 00000000..28c85ff1
--- /dev/null
+++ b/changelog/unreleased/2026-10-16-agent-api-amsp.md
@@ -0,0 +1,62 @@
+# External programs can talk to an Agent: the Agent API, the AMSP stream and the amsp client
+
+- **Date:** 2026-10-16
+- **Type:** feature
+- **Scope:** `server`, `web`, `cli`, `amsp`, `docs`
+
+[中文版](2026-10-16-agent-api-amsp.zh.md)
+
+Ported from upstream PenguinHarness (#1000, commit `473c9470`).
+
+A Project owner could open one agent to programs outside Adelie. A program sent its input to `POST /api/amsp/v1/agents/:projectId/:agentId/runs`, read the run as it happened as an AMSP event stream, and continued the conversation by its Session id. The runs used the Project's models and credentials, were recorded like any conversation, and appeared in the sidebar's **Background** folder. A new package, `@lmliheng/amsp`, carried the protocol's types and a TypeScript client for Node and browsers.
+
+## The Agent API
+
+- Each agent got its own switch, off by default, an optional **keyless access** switch, also off by default, and an **API approval mode**, `allow-all` by default. They were stored in the server's database, in the new `agent_api` and `agent_api_keys` tables, outside the agent's state and outside the Project file, so an agent could neither expose itself nor loosen its own approvals.
+- Keys were minted per agent, named, and shown once: `penguin_` followed by 43 base64url characters, stored as SHA-256 and listed by their first 16 characters. A key ran its own agent and read, aborted and answered the approvals of that agent's API conversations, and opened nothing else. Each run that presented a key stamped its last use.
+- The public routes were mounted under `/api/amsp/v1`, outside the sign-in cookie: `GET /agents/:projectId/:agentId`, `POST /agents/:projectId/:agentId/runs`, `GET /sessions/:sessionId`, `POST /sessions/:sessionId/abort` and `POST /sessions/:sessionId/approvals/:toolCallId`. Any other path under the prefix answered a JSON `404` `not_found`. The key and the switches were checked before the body was read.
+- A run without `session_id` created a conversation with `session_meta.source` `api` and the index row's `client` `api`, using the Project's default model, the server's new-chat sandbox and the agent's API approval mode, copied onto the conversation when it was created. `session_id` continued an API conversation of the same agent; any other id was `404` `session_not_found`. A conversation whose first run had not written its Trace read as `api` from its row, in the list and when it was rebuilt after a restart.
+- When the approval mode asked, the request streamed to the caller as `approval.requested`, and the conversation in the Web App could answer it too; the first answer counted. A caller that disconnected aborted its run, and its pending approvals were denied. `POST …/abort` aborted while keeping the stream open for the final `run.done`.
+- A busy conversation answered `409`; a fifth concurrent run of one agent answered `429` `too_many_runs` with `Retry-After: 2`.
+- The CORS preflight was answered for any origin. `Access-Control-Allow-Origin: *` went only on a request carrying `Authorization`, the server-wide `413` and `415` refusals included, so a page on another origin could not drive an agent through keyless access.
+- The administrator's `agentApiEnabled` setting in `/api/admin/settings`, on by default, refused every Agent API request with `403` `agent_api_disabled` when off, keeping the agents' settings and keys.
+- The routes under `/api/projects/:projectId/agents/:agentId/api` let any member read an agent's settings, the administrator's switch included as `serverEnabled`, and let the owner change them and create and delete keys; `POST …/api/try` ran the agent for the owner's sign-in and streamed the same AMSP response. The agents list carried `apiEnabled`.
+- Changing an agent's exposure took a person's sign-in. The local API token, which every tool subprocess of a server-driven Session holds, could read an agent's settings and keys, but `PUT …/api`, `POST …/api/keys`, `DELETE …/api/keys/:keyId`, `POST …/api/try` and a `PUT /api/admin/settings` carrying `agentApiEnabled` refused it with `403` `human_required`, the code the agent browser already gave the token, and wrote nothing, so an agent could not switch on its own exposure from its shell. This narrowed the credential the harness handed an agent; the sandbox remained the boundary.
+
+## The AMSP stream
+
+- AMSP (Agent Message Stream Protocol) streamed one run of an agent, one Task, the way MMSP streams one model call: SSE `data:` lines, `data: [DONE]` at the end, `: keep-alive` after 15 seconds of silence, bytes as base64. Events were flat objects named `<subject>.<phase>`: `run.*`, `context.opened`, `mcp_connect.*`, `tools.ready`, `request.*`, `K.delta` / `K.done` items, `approval.*`, `compaction.*` and `hook.fired`.
+- The server translated the Session's live stream into it: OmniMessage records and server events. Fragments and complete items were forwarded as the engine produced them, `partial_*` `stop` was not sent, and OmniMessage gained no field.
+- `run.done` was the single terminal event and always arrived, errors included, with the run's status, error, Request count, token usage and the Session's running total. Errors before the stream used the server's error envelope with fixed status codes.
+- New event types and optional fields were to be added within `/v1`, and a change to a field's meaning would be `/v2`; clients were required to ignore event types they did not know.
+
+## The amsp client
+
+- `@lmliheng/amsp` was a new public package with no runtime dependencies, for Node 24 and browsers. It exported the AMSP wire types, which the server imported, and `AgentClient`.
+- `client.run()` returned a run to iterate for its events, with `session`, `result()` and `abort()`; `client.ask()` returned the result alone. `onApproval` answered approval requests, and without it they were denied. The client also offered `agent()`, `session()`, `abort()` and `approve()`, the `AmspHttpError` and `AmspStreamError` errors, `parseArguments` for a tool call's JSON arguments, `readSse`, the SSE reader, and `RunCollector`, which folded the events a program read itself into the same result.
+
+## The Web App
+
+- The agent settings page gained an **API** tab: **Enable API access**, the approval mode for API conversations, the Base URL and Agent ID to copy, keys created with a one-time display and deleted from a list, **Allow keyless access**, which asked for confirmation with a warning before it went on, and curl and TypeScript examples. While the administrator had the Agent API off, the tab disabled its switch and said why, to every member.
+- The API tab ended with **Try it**, for the owner: an input prefilled with "What time is it now?" and a Run button that sent one real API run through `POST /api/projects/:projectId/agents/:agentId/api/try` — the owner's sign-in standing in for a key, the same handler behind it — and showed the stream as a program would receive it in one output box: a header with the `session_id` and a Rendered / Raw switch — numbered rows with each item's fragments merged into what they add up to (the answer is the `text` row), or the numbered raw `data:` lines — over a strip with the `run.done` status, Request count, tokens (cache reads and writes when there were any) and elapsed time; running again continued that conversation, Stop aborted it through the Session's abort route, and an approval the mode asked for was answered inline.
+- The Agents page marked an agent whose API was on with an API icon. **Settings › Server** gained an **Agent API** page with the administrator's **Allow the Agent API** switch, which asked before turning off.
+- Rows in the sidebar's **Background** folder (API, scheduled, subagent and CLI conversations) no longer showed the green unread dot after a run; only a person's own conversations did. They still showed the hourglass while running.
+
+## The CLI
+
+- `penguin agent api` showed and changed an agent's API from a terminal: `status`, `enable`, `disable` and `set` (with `--open` / `--no-open` and `--approve <mode>`), `keys ls`, `keys create` (the key alone on stdout), `keys rm`, and `server on|off` for the administrator's switch. `--agent-id` was required, with no default, and `status` showed the administrator's switch to any member. Turning keyless access on with `--open` printed a warning on stderr.
+- The CLI still authenticated with `PENGUIN_API_TOKEN`, else the `api-token` file. When the server refused a request to that token with `403` `human_required`, the CLI sent the same request once more with the person's stored sign-in, the `<root>/cli-session.json` session written by `penguin auth login` or `penguin auth token`, as the session cookie. It did so only for a loopback server, only with a sign-in to a loopback server, and never from inside a Session. The `penguin agent api` writes therefore worked after `penguin auth login`; with no sign-in, or one the server no longer accepted, they printed the command to run and exited 1.
+
+## Docs
+
+- Two new reference pages: **Agent API**, on turning an agent's API on, the approval mode, keys, keyless access, the routes, errors, curl, the client in Node and browsers, and the CLI; and **AMSP**, the protocol's transport, grammar, every event, examples, errors, the mapping from OmniMessage and the versioning rule.
+- **Server API** gained the agent API settings routes, `agentApiEnabled`, `apiEnabled`, `client` `api` and the CORS exception for `/api/amsp/v1`; **CLI Reference** gained `penguin agent api`; **Agents** gained the **API** tab; **Settings** gained the **Agent API** page; **OmniMessage** said that AMSP is a projection of it and changed nothing in it.
+- **Agent API**, **Server API**, **CLI Reference** and **Security Model** said that changing an agent's exposure took a person's sign-in and was refused to the local API token with `human_required`, that this was not a boundary, and when the CLI sent a stored sign-in instead.
+- The `penguin-sdk`, `penguin-orchestration` and `agent-initialization` skills said that the server refused the `penguin agent api` writes to an agent's token, told the agent never to sign in to get past that, and put `penguin auth login` first in the steps for the user. The `agent-tuning` plugin moved to `2026.10.09.2`.
+
+## Compatibility
+
+No compatibility code was added; these changes were accepted as they are:
+
+- Two new tables, `agent_api` and `agent_api_keys` (migration 14). An earlier server never reads them and serves no `/api/amsp` route, so after a rollback callers get `404` until a build that knows the tables is back. Rolling the migration back deletes every agent's API settings and keys.
+- Conversations the API creates store `client` `api` in the Session index, a column that takes new values without a migration.
diff --git a/changelog/unreleased/2026-10-16-agent-api-amsp.zh.md b/changelog/unreleased/2026-10-16-agent-api-amsp.zh.md
new file mode 100644
index 00000000..49b59559
--- /dev/null
+++ b/changelog/unreleased/2026-10-16-agent-api-amsp.zh.md
@@ -0,0 +1,60 @@
+# 外部程序可以与 Agent 对话:Agent API、AMSP 事件流与 amsp 客户端
+
+- **Date:** 2026-10-16
+- **Type:** feature
+- **Scope:** `server`, `web`, `cli`, `amsp`, `docs`
+
+[English](2026-10-16-agent-api-amsp.md)
+
+Project 所有者可以把某一个 Agent 开放给 Adelie 之外的程序。程序把输入发到 `POST /api/amsp/v1/agents/:projectId/:agentId/runs`,以 AMSP 事件流实时读取这次运行,再凭 Session id 延续对话。这些运行使用 Project 的模型与凭据,像其他对话一样被记录,并出现在侧边栏的**后台会话**折叠夹中。新增的 `@lmliheng/amsp` 包含该协议的类型和一个可在 Node 与浏览器中使用的 TypeScript 客户端。
+
+## Agent API
+
+- 每个 Agent 有了自己的开关(缺省关闭)、可选的**无密钥访问**开关(同样缺省关闭)和 **API 审批模式**(缺省 `allow-all`)。它们保存在服务器数据库新增的 `agent_api` 与 `agent_api_keys` 表中,不在 Agent 的状态里,也不在 Project 文件里,因此 Agent 既不能自行对外开放,也不能放宽自己的审批。
+- 密钥按 Agent 签发,各有名字,只显示一次:`penguin_` 加 43 个 base64url 字符,以 SHA-256 保存,列表中显示其前 16 个字符。密钥只能运行它所属的 Agent,并读取、中止该 Agent 的 API 会话、回答其审批,此外不能访问任何东西。每次出示密钥的运行都会记下它的最近使用时间。
+- 公开路由挂在 `/api/amsp/v1` 之下,不经登录 Cookie:`GET /agents/:projectId/:agentId`、`POST /agents/:projectId/:agentId/runs`、`GET /sessions/:sessionId`、`POST /sessions/:sessionId/abort` 和 `POST /sessions/:sessionId/approvals/:toolCallId`。该前缀下的其他路径返回 JSON 形式的 `404` `not_found`。密钥和各项开关在读取请求体之前检查。
+- 不带 `session_id` 的运行会新建一个会话,其 `session_meta.source` 为 `api`、索引行的 `client` 为 `api`,使用 Project 的默认模型、服务器的新对话沙箱和该 Agent 的 API 审批模式(在会话创建时复制到会话上)。`session_id` 延续同一个 Agent 的 API 会话;其他 id 返回 `404` `session_not_found`。首次运行尚未写下 Trace 的会话按其索引行读作 `api`,在列表中如此,重启后重建时也如此。
+- 审批模式需要询问时,确认请求以 `approval.requested` 流向调用方,Web App 中的该会话也能回答,以先回答的为准。调用方断开连接即中止其运行,待审批的调用被拒绝。`POST …/abort` 中止运行,同时保持事件流打开,以送出最后的 `run.done`。
+- 正忙的会话返回 `409`;同一个 Agent 的第五个并发运行返回 `429` `too_many_runs`,并带 `Retry-After: 2`。
+- CORS 预检对任何来源都应答。`Access-Control-Allow-Origin: *` 只在带 `Authorization` 的请求上返回,服务器全局的 `413` 与 `415` 拒绝也不例外,所以其他来源的页面无法借无密钥访问驱动 Agent。
+- 管理员在 `/api/admin/settings` 中的 `agentApiEnabled` 设置缺省开启;关闭后所有 Agent API 请求都以 `403` `agent_api_disabled` 拒绝,各 Agent 的设置与密钥保留。
+- `/api/projects/:projectId/agents/:agentId/api` 下的路由让任何成员读取 Agent 的设置(包括以 `serverEnabled` 给出的管理员开关),让所有者修改设置、创建和删除密钥;`POST …/api/try` 以所有者的登录身份运行 Agent,返回同样的 AMSP 事件流。Agent 列表带上了 `apiEnabled`。
+- 改变 Agent 的对外暴露需要人的登录。服务器驱动的 Session 的每个工具子进程都持有本地 API token;它能读取 Agent 的设置与密钥,但 `PUT …/api`、`POST …/api/keys`、`DELETE …/api/keys/:keyId`、`POST …/api/try` 以及带 `agentApiEnabled` 的 `PUT /api/admin/settings` 都以 `403` `human_required`(Agent 浏览器拒绝 token 时已在用的错误码)拒绝它,且不写入任何内容,因此 Agent 无法在自己的 shell 里开启自己的对外暴露。这收窄了 harness 交给 Agent 的凭据;边界仍是沙盒。
+
+## AMSP 事件流
+
+- AMSP(Agent Message Stream Protocol)流式传输 Agent 的一次运行(一个 Task),正如 MMSP 流式传输一次模型调用:SSE 的 `data:` 行,以 `data: [DONE]` 收尾,静默 15 秒时发送 `: keep-alive`,字节以 base64 传送。事件是以 `<subject>.<phase>` 命名的扁平对象:`run.*`、`context.opened`、`mcp_connect.*`、`tools.ready`、`request.*`、`K.delta` / `K.done` 内容项、`approval.*`、`compaction.*` 和 `hook.fired`。
+- 服务器把 Session 的实时流(OmniMessage 记录与服务器事件)翻译成 AMSP。分片和完整内容项都按引擎产出的原样转发,`partial_*` 的 `stop` 不发送,OmniMessage 没有增加任何字段。
+- `run.done` 是唯一的终止事件,总会到达(出错时也一样),带有运行的状态、错误、Request 次数、Token 用量和 Session 的累计值。事件流开始之前的错误沿用服务器的错误信封和固定的状态码。
+- 新的事件类型和可选字段在 `/v1` 之内增加,改变字段含义则属于 `/v2`;客户端须忽略不认识的事件类型。
+
+## amsp 客户端
+
+- `@lmliheng/amsp` 是新的公开包,没有运行时依赖,适用于 Node 24 和浏览器。它导出 AMSP 的传输类型(服务器也引用这些类型)和 `AgentClient`。
+- `client.run()` 返回一个可迭代取得事件的运行,带有 `session`、`result()` 和 `abort()`;`client.ask()` 只返回结果。`onApproval` 回答审批请求,没有它时一律拒绝。客户端还提供 `agent()`、`session()`、`abort()` 和 `approve()`,`AmspHttpError` 与 `AmspStreamError` 两种错误,解析工具调用 JSON 参数的 `parseArguments`、SSE 读取器 `readSse`,以及把程序自行读取的事件归并为同样结果的 `RunCollector`。
+
+## Web App
+
+- Agent 设置页新增 **API** 标签页:**开启 API 访问**、API 会话的审批模式、可复制的 Base URL 和 Agent ID、只显示一次并可在列表中删除的密钥、**允许无密钥访问**(打开前先弹出带警示的确认),以及 curl 和 TypeScript 示例。管理员关闭 Agent API 期间,标签页的开关不可用,并向所有成员说明原因。
+- API 标签末尾为所有者增加了**试一试**:输入框预填「现在几点了?」,「运行」经 `POST /api/projects/:projectId/agents/:agentId/api/try` 以所有者的登录身份代替密钥、经同一个处理器发起一次真实的 API 运行,并在一个输出框里按程序会收到的样子显示事件流:标题栏为 `session_id` 与「渲染」/「原始」切换——带行号的逐条目行(同一条目的增量片段合并为拼好的内容,回答即 `text` 行)或带行号的原始 `data:` 行——框底一栏为 `run.done` 的状态、Request 次数、Token(有缓存读写时一并显示)与用时;再次运行即续接该会话,「停止」经会话的中止路由中止,审批模式询问时可在行内作答。
+- 智能体页面为已开启 API 的 Agent 加上 API 图标。**设置 › 服务器**新增 **Agent API** 页,其中是管理员的**允许 Agent API** 开关,关闭前会先确认。
+- 侧边栏**后台会话**折叠夹中的会话(API、定时任务、子智能体与 CLI 会话)运行结束后不再显示未读绿点,只有你自己的对话才显示;运行期间仍显示沙漏。
+
+## CLI
+
+- `penguin agent api` 在终端里查看和修改 Agent 的 API:`status`、`enable`、`disable` 和 `set`(带 `--open` / `--no-open` 与 `--approve <mode>`)、`keys ls`、`keys create`(stdout 上只有密钥本身)、`keys rm`,以及管理员开关 `server on|off`。`--agent-id` 必填、没有默认值;`status` 向任何成员显示管理员开关。用 `--open` 开启无密钥访问后,会在 stderr 打印一条警告。
+- CLI 照旧以 `PENGUIN_API_TOKEN` 认证,没有时用 `api-token` 文件。服务器以 `403` `human_required` 拒绝携带该 token 的请求时,CLI 改用人保存的登录——`penguin auth login` 或 `penguin auth token` 写入 `<root>/cli-session.json` 的会话,以会话 Cookie 发送——把同一请求再发一次。只对回环地址上的服务器这样做,只用对回环地址服务器的登录,且从不在 Session 内这样做。`penguin agent api` 的修改命令因此在 `penguin auth login` 之后可用;没有登录或服务器不再接受该登录时,打印应运行的命令并以退出码 1 退出。
+
+## 文档
+
+- 新增两个参考页面:**Agent API**,讲开启 Agent 的 API、审批模式、密钥、无密钥访问、路由、错误、curl、在 Node 和浏览器中使用客户端,以及 CLI;**AMSP**,讲协议的传输、语法、全部事件、示例、错误、从 OmniMessage 的映射和版本规则。
+- **Server API** 补充了 Agent API 设置路由、`agentApiEnabled`、`apiEnabled`、`client` 的 `api` 取值和 `/api/amsp/v1` 的 CORS 例外;**CLI 参考**补充了 `penguin agent api`;**智能体**补充了 **API** 标签页;**设置**补充了 **Agent API** 页;**OmniMessage** 说明 AMSP 是它的投影,它本身没有任何改变。
+- **Agent API**、**Server API**、**CLI 参考**和**安全模型**说明:改变 Agent 的对外暴露需要人的登录,本地 API token 会以 `human_required` 被拒绝,这不是边界;并说明 CLI 何时改用保存的登录。
+- `penguin-sdk`、`penguin-orchestration` 和 `agent-initialization` 三个 Skill 写明服务器会以 Agent 的 token 拒绝 `penguin agent api` 的修改命令,要求 Agent 绝不为绕过拒绝而自行登录,并在交给用户的步骤里先写 `penguin auth login`。`agent-tuning` 插件升到 `2026.10.09.2`。
+
+## 兼容性
+
+没有加入任何兼容代码;以下变化按原样接受:
+
+- 新增 `agent_api` 和 `agent_api_keys` 两张表(migration 14)。旧版服务器从不读取它们,也不提供 `/api/amsp` 路由,所以回滚之后调用方会得到 `404`,直到认识这两张表的版本回来。回滚该 migration 会删除所有 Agent 的 API 设置和密钥。
+- API 创建的会话在 Session 索引中记为 `client` `api`;这一列接受新取值,无需 migration。
diff --git a/changelog/unreleased/2026-10-16-skills-sdk-or-api.md b/changelog/unreleased/2026-10-16-skills-sdk-or-api.md
new file mode 100644
index 00000000..257455f9
--- /dev/null
+++ b/changelog/unreleased/2026-10-16-skills-sdk-or-api.md
@@ -0,0 +1,20 @@
+# Skills ask whether a program embeds its agent with the SDK or calls it over the Agent API
+
+- **Date:** 2026-10-16
+- **Type:** feature
+- **Scope:** `plugins`, `docs`
+
+[中文版](2026-10-16-skills-sdk-or-api.zh.md)
+
+Ported from upstream PenguinHarness (commit `473c9470`).
+
+A program reaches an agent in one of two ways: embedded with the SDK, `@lmliheng/penguin-core`, which runs the basic agent loop without the server, or through the server's Agent API over AMSP, with the `@lmliheng/amsp` client or curl. The skills that build agent applications and create agents described both ways and asked the user which one before building. The `agent-development` and `agent-tuning` plugins moved to `2026.10.16.1`.
+
+## Details
+
+- **`penguin-sdk`** opened with *Two ways to reach an agent*: for each way, what it is, what it gives, what it lacks or requires, and when to choose it. Whenever the user asked to connect a program to an agent, or to build a program with an agent in it, the skill asked which way first, even when the request was otherwise concrete. The question was one a2ui choice block, which the Web App rendered as two buttons and the CLI and the messaging channels as a numbered list. It was not asked when the user's message or an earlier answer had already chosen, nor for workflows or Remote-control bots. After it, the skill's no-follow-up-questions default held as before.
+- The existing SDK content moved, unchanged, under *The SDK path*, its verification steps included. A new *The API path* section and `reference/agent-api.md` covered the other way: the steps the Project's owner takes on the Agent's **API** tab or with `penguin agent api`, the approval mode to suggest, the Base URL (`localhost`, not `127.0.0.1`), the Agent ID as `<projectId>/<agentId>`, the `AgentClient` with `ask`, `run`, Session continuation and `onApproval`, curl, the errors, and the checks before handing over.
+- The agent never turned on an Agent's API access or keyless access, never changed its approval mode or the server-wide switch, and never created or deleted keys, although the token in its shell could have allowed it. It asked the user and showed where. The key stayed in the `ADELIE_AGENT_KEY` environment variable, out of the code and out of the chat.
+- **`agent-initialization`** asked the same question when the requested agent was for a program. On the SDK path it handed over to `penguin-sdk` and configured the program's embedded agent; on the API path it created the Agent in the Project and reported the owner's steps, the Agent ID and the Base URL.
+- **`penguin-orchestration`** listed `penguin agent api` among its cautions: the read-only commands were the agent's to run, the changing ones the owner's.
+- The `agent-development` plugin's descriptions and the docs' Skills page named the Agent API next to the SDK.
diff --git a/changelog/unreleased/2026-10-16-skills-sdk-or-api.zh.md b/changelog/unreleased/2026-10-16-skills-sdk-or-api.zh.md
new file mode 100644
index 00000000..f1d7ea68
--- /dev/null
+++ b/changelog/unreleased/2026-10-16-skills-sdk-or-api.zh.md
@@ -0,0 +1,20 @@
+# Skill 先问程序是用 SDK 内嵌 Agent,还是经 Agent API 调用
+
+- **Date:** 2026-10-16
+- **Type:** feature
+- **Scope:** `plugins`, `docs`
+
+[English](2026-10-16-skills-sdk-or-api.md)
+
+移植自上游 PenguinHarness(提交 `473c9470`)。
+
+程序接入 Agent 有两种方式:一是用 SDK `@lmliheng/penguin-core` 内嵌,完全脱离服务器,只提供最基础的 Agent 循环;二是经服务器的 Agent API,按 AMSP 协议,用 `@lmliheng/amsp` 客户端或 curl 调用。负责构建 Agent 应用与创建 Agent 的 Skill 写明了这两种方式,并在动手之前先问用户选哪一种。`agent-development` 与 `agent-tuning` 插件升到 `2026.10.16.1`。
+
+## 细节
+
+- **`penguin-sdk`** 以 *Two ways to reach an agent* 一节开篇:逐一说明每种方式是什么、能得到什么、缺什么或需要什么、何时选用。用户要把程序接入 Agent,或要构建内含 Agent 的程序时,即使需求已经具体,Skill 也先问用哪种方式。这个问题是一个 a2ui 选项块,Web App 渲染为两个按钮,CLI 与消息渠道显示为编号列表。用户的消息或此前的回答已经选定时不再问,工作流与远程控制机器人也不问。问过之后,Skill「不追问」的默认规则照旧。
+- 原有的 SDK 内容原样移入 *The SDK path* 一节,验证步骤也在其中。新增的 *The API path* 一节与 `reference/agent-api.md` 覆盖另一种方式:Project 所有者在 Agent 的 **API** 标签页或用 `penguin agent api` 要做的步骤、建议的审批模式、Base URL(用 `localhost`,不用 `127.0.0.1`)、形如 `<projectId>/<agentId>` 的 Agent ID、`AgentClient` 的 `ask` 与 `run`、按 Session 续接对话与 `onApproval`、curl、错误码,以及交付前的检查。
+- Agent 从不自行开启某个 Agent 的 API 访问或无密钥访问,不修改其审批模式或服务器总开关,也不创建、删除密钥,尽管它 shell 里的令牌可能允许这样做;它请用户来做,并指明在哪里做。密钥只放在环境变量 `ADELIE_AGENT_KEY` 里,不进代码,也不进对话。
+- **`agent-initialization`** 在所要的 Agent 供程序使用时问同一个问题。选 SDK 时转交 `penguin-sdk`,配置程序内嵌的 Agent;选 API 时在 Project 中创建 Agent,并在报告里写明所有者要做的步骤、Agent ID 与 Base URL。
+- **`penguin-orchestration`** 在注意事项里写明 `penguin agent api`:只读命令 Agent 可以自己运行,修改类命令归所有者。
+- `agent-development` 插件的描述与文档的 Skill 页在 SDK 旁写上了 Agent API。
diff --git a/packages/amsp/README.md b/packages/amsp/README.md
new file mode 100644
index 00000000..6922b692
--- /dev/null
+++ b/packages/amsp/README.md
@@ -0,0 +1,65 @@
+# @lmliheng/amsp
+
+The client of a Adelie agent's API, and the types of AMSP (Agent Message Stream Protocol), the event stream that API serves. No runtime dependencies; runs in Node 24 and in current browsers on `fetch`, `ReadableStream`, `TextDecoder` and `AbortController`.
+
+A Project owner turns an agent's API on in the Adelie Web App (the agent's **API** tab) and mints a key there. A program then runs the agent, reads the run as it happens, and continues the conversation by its Session id:
+
+```ts
+import { AgentClient } from "@lmliheng/amsp";
+
+const client = new AgentClient({
+ baseUrl: "http://localhost:7364/api/amsp/v1",
+ agent: "demo/coder", // <projectId>/<agentId>
+ apiKey: process.env.PENGUIN_AGENT_KEY,
+});
+
+const run = client.run({ input: "Summarize README.md" });
+for await (const event of run) {
+ if (event.type === "text.delta") process.stdout.write(event.text);
+}
+const first = await run.result();
+
+const second = await client.ask({
+ sessionId: first.sessionId,
+ input: "Now list its headings",
+ onApproval: () => "allow", // without a callback, approval requests are denied
+});
+console.log(second.text, second.usage.total);
+```
+
+- `run()` starts the run and returns it: iterate it once for the events, await `session` for the Session id, `result()` for the outcome, and call `abort()` to have the server abort it. `ask()` returns the result alone.
+- `result()` resolves for every run that reached `run.done`, whatever its `status`. A refusal before the stream rejects with `AmspHttpError` (`status`, `code`, `message`); a stream that ends or breaks before `run.done` rejects with `AmspStreamError`; aborting the `signal` rejects with its reason.
+- `onApproval` answers each `approval.requested`, and the client posts the answer; `parseArguments` reads a tool call's JSON arguments.
+- `agent()`, `session(id)`, `abort(id)` and `approve(id, toolCallId, decision)` call the API's other routes; `readSse` is the SSE reader, for a program that reads a run's body itself.
+- Every AMSP event type is exported (`AmspEvent`, `RunDone`, `ToolCallDone`, …). Events of a type the client does not know are passed through.
+
+## The reader without the client
+
+A program that sends the request itself — its own `fetch`, its own credentials or URL — reads the body with `readSse` and folds the events with `RunCollector`, which `AgentClient` uses for `result()`:
+
+```ts
+import { readSse, RunCollector } from "@lmliheng/amsp";
+import type { AmspEvent } from "@lmliheng/amsp";
+
+const collector = new RunCollector();
+for await (const data of readSse(response.body!)) {
+ if (data === "[DONE]") break;
+ collector.add(JSON.parse(data) as AmspEvent);
+}
+const result = collector.result(); // throws AmspStreamError when the stream ended before run.done
+```
+
+## Documentation
+
+- [Agent API](https://penguin.ooo/docs/agent-api): turning an agent's API on, keys, approval modes, routes, errors, the client in Node and browsers
+- [AMSP](https://penguin.ooo/docs/amsp): the protocol, event by event
+
+## Development
+
+```bash
+pnpm --filter @lmliheng/amsp build # tsup → dist/ (exports point at dist)
+pnpm --filter @lmliheng/amsp typecheck
+pnpm --filter @lmliheng/amsp test
+```
+
+Part of [Adelie](https://github.com/Prism-Shadow/penguin-harness) · Apache-2.0
diff --git a/packages/amsp/package.json b/packages/amsp/package.json
new file mode 100644
index 00000000..53d84b2c
--- /dev/null
+++ b/packages/amsp/package.json
@@ -0,0 +1,41 @@
+{
+ "name": "@lmliheng/amsp",
+ "version": "0.4.1",
+ "type": "module",
+ "description": "AMSP (Agent Message Stream Protocol): the wire types of an Adelie agent's API and a zero-dependency client for Node 24 and browsers.",
+ "license": "Apache-2.0",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/Prism-Shadow/penguin-harness.git",
+ "directory": "packages/amsp"
+ },
+ "engines": {
+ "node": ">=24"
+ },
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "import": "./dist/index.js"
+ }
+ },
+ "main": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "sideEffects": false,
+ "scripts": {
+ "typecheck": "tsc --noEmit -p tsconfig.json",
+ "test": "vitest run --passWithNoTests",
+ "build": "tsup"
+ },
+ "devDependencies": {
+ "tsup": "^8.3.0",
+ "typescript": "^5.6.0",
+ "vitest": "^3.2.6"
+ },
+ "files": [
+ "dist",
+ "LICENSE"
+ ],
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/packages/amsp/src/client.ts b/packages/amsp/src/client.ts
new file mode 100644
index 00000000..bfcfc095
--- /dev/null
+++ b/packages/amsp/src/client.ts
@@ -0,0 +1,374 @@
+/**
+ * The client of one Agent's API: runs it, continues its Sessions, answers its approvals.
+ *
+ * Only `fetch`, `Headers`, `ReadableStream`, `TextDecoder` and `AbortController` are used, so the
+ * same code runs in Node 24 and in a browser.
+ */
+import { RunCollector, type RunResult } from "./collect.js";
+import { AmspHttpError, AmspStreamError, httpError } from "./errors.js";
+import { sseData } from "./sse.js";
+import type {
+ AgentInfo,
+ AgentResponse,
+ AmspEvent,
+ ApprovalRequest,
+ ApprovalRequested,
+ InputItem,
+ RunRequest,
+ SessionInfo,
+ SessionResponse,
+} from "./types.js";
+
+export interface AgentClientOptions {
+ /** The server's AMSP base URL, e.g. `http://localhost:7364/api/amsp/v1`. */
+ baseUrl: string;
+ /** The Agent, as `<projectId>/<agentId>`, e.g. `demo/coder`. */
+ agent: string;
+ /** The Agent's API key, sent as a Bearer token. Omit it only for an Agent that allows keyless access; no environment variable is read for it. */
+ apiKey?: string;
+ /** The `fetch` to send requests with; the global one by default. */
+ fetch?: typeof fetch;
+ /** Extra headers for every request. A browser sends a cross-origin request only with the headers the server allows (`Authorization`, `Content-Type`). */
+ headers?: Record<string, string>;
+}
+
+export interface RunOptions {
+ /** The new user input: text, or text and image items. */
+ input: string | InputItem[];
+ /** Continues this Session; omitted, the run starts a new one, named by `run.started`. */
+ sessionId?: string;
+ /** Aborting it closes the connection, which aborts the run on the server, and rejects the run with the signal's reason. */
+ signal?: AbortSignal;
+ /** Called for every `approval.requested`; the answer is POSTed for you. Absent, or throwing, = `"deny"`. */
+ onApproval?: (
+ req: ApprovalRequested,
+ ctx: { sessionId: string },
+ ) => Promise<"allow" | "deny"> | "allow" | "deny";
+}
+
+/**
+ * One run of the Agent, under way from the moment `run()` returns. Iterate it for the events as
+ * they arrive — once; events are kept until they are read, so use `ask()` when only the result
+ * matters. `result()` resolves when the stream ends. Approvals are answered as they arrive,
+ * whether or not anyone iterates. Leaving the loop early stops the iteration, not the run; call
+ * `abort()` or abort the signal for that.
+ */
+export interface Run extends AsyncIterable<AmspEvent> {
+ /** The Session id, from `run.started`, before any other event. */
+ readonly session: Promise<string>;
+ /** The outcome. Rejects with an {@link AmspHttpError} on a refusal, an {@link AmspStreamError} when the stream broke, or the abort reason. */
+ result(): Promise<RunResult>;
+ /** Asks the server to abort the run. The stream stays open and ends with `run.done` `aborted`. */
+ abort(): Promise<void>;
+}
+
+/** How every request is sent: the base URL, the key and extra headers, the chosen `fetch`. */
+class Transport {
+ readonly #baseUrl: string;
+ readonly #headers: Record<string, string>;
+ readonly #fetch: typeof fetch | undefined;
+
+ constructor(opts: AgentClientOptions) {
+ this.#baseUrl = opts.baseUrl.replace(/\/+$/, "");
+ this.#headers = {
+ ...opts.headers,
+ ...(opts.apiKey ? { Authorization: `Bearer ${opts.apiKey}` } : {}),
+ };
+ this.#fetch = opts.fetch;
+ }
+
+ /** Sends one request; an answer other than 2xx is thrown as an {@link AmspHttpError}. */
+ async send(
+ method: "GET" | "POST",
+ path: string,
+ init: { body?: unknown; accept?: string; signal?: AbortSignal } = {},
+ ): Promise<Response> {
+ const headers: Record<string, string> = { ...this.#headers };
+ if (init.body !== undefined) headers["Content-Type"] = "application/json";
+ if (init.accept !== undefined) headers.Accept = init.accept;
+ // Called bare: a browser's fetch throws "Illegal invocation" when called as another object's method.
+ const fetchImpl = this.#fetch ?? globalThis.fetch;
+ const response = await fetchImpl(this.#baseUrl + path, {
+ method,
+ headers,
+ ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}),
+ ...(init.signal ? { signal: init.signal } : {}),
+ });
+ if (!response.ok) throw await httpError(response);
+ return response;
+ }
+}
+
+const sessionPath = (sessionId: string) => `/sessions/${encodeURIComponent(sessionId)}`;
+
+const approvalPath = (sessionId: string, toolCallId: string) =>
+ `${sessionPath(sessionId)}/approvals/${encodeURIComponent(toolCallId)}`;
+
+/** One block of the stream as an event; anything that is not an object with a `type` breaks the stream. */
+function parseEvent(data: string): AmspEvent {
+ let event: unknown;
+ try {
+ event = JSON.parse(data);
+ } catch (err) {
+ throw new AmspStreamError(
+ `The stream carried a block that is not JSON: ${data.slice(0, 200)}`,
+ {
+ cause: err,
+ },
+ );
+ }
+ if (
+ event === null ||
+ typeof event !== "object" ||
+ typeof (event as { type?: unknown }).type !== "string"
+ ) {
+ throw new AmspStreamError(
+ `The stream carried a block that is not an event: ${data.slice(0, 200)}`,
+ );
+ }
+ return event as AmspEvent;
+}
+
+type Outcome = { ok: true } | { ok: false; error: unknown };
+
+const END: IteratorResult<AmspEvent> = { value: undefined, done: true };
+
+class AgentRun implements Run {
+ readonly session: Promise<string>;
+ readonly #transport: Transport;
+ readonly #result: Promise<RunResult>;
+ /** Aborted by the caller's signal, or by an approval that could not be answered. */
+ readonly #control = new AbortController();
+ /** Events not yet read by the iterator; null when nobody will read them (`ask()`, or after the loop left). */
+ #queue: AmspEvent[] | null;
+ #iterated = false;
+ #waiter: {
+ resolve: (result: IteratorResult<AmspEvent>) => void;
+ reject: (error: unknown) => void;
+ } | null = null;
+ #outcome: Outcome | null = null;
+ #resolveSession!: (sessionId: string) => void;
+ #rejectSession!: (error: unknown) => void;
+
+ constructor(transport: Transport, agentPath: string, opts: RunOptions, iterable: boolean) {
+ this.#transport = transport;
+ this.#queue = iterable ? [] : null;
+ this.session = new Promise<string>((resolve, reject) => {
+ this.#resolveSession = resolve;
+ this.#rejectSession = reject;
+ });
+ // Each failure reaches whoever awaits it; one nobody awaits is not an unhandled rejection.
+ this.session.catch(() => {});
+ this.#result = this.#drive(agentPath, opts);
+ this.#result.catch(() => {});
+ }
+
+ result(): Promise<RunResult> {
+ return this.#result;
+ }
+
+ async abort(): Promise<void> {
+ let sessionId: string;
+ try {
+ sessionId = await this.session;
+ } catch {
+ return; // refused or broken before the run started: nothing runs
+ }
+ if (this.#outcome !== null) return;
+ await this.#transport.send("POST", `${sessionPath(sessionId)}/abort`);
+ }
+
+ [Symbol.asyncIterator](): AsyncIterator<AmspEvent> {
+ if (this.#iterated) throw new TypeError("A run's events can be iterated once.");
+ this.#iterated = true;
+ return {
+ next: () => this.#next(),
+ return: () => {
+ this.#queue = null;
+ return Promise.resolve(END);
+ },
+ };
+ }
+
+ #next(): Promise<IteratorResult<AmspEvent>> {
+ if (this.#queue === null) return Promise.resolve(END);
+ // Aborted: reads fail at once and what was buffered is dropped, as an aborted fetch body does.
+ // A run that completed is not undone by an abort that came after it.
+ if (this.#control.signal.aborted && this.#outcome?.ok !== true) {
+ this.#queue = null;
+ return Promise.reject(this.#control.signal.reason);
+ }
+ const event = this.#queue.shift();
+ if (event !== undefined) return Promise.resolve({ value: event, done: false });
+ const outcome = this.#outcome;
+ if (outcome !== null) {
+ this.#queue = null;
+ return outcome.ok ? Promise.resolve(END) : Promise.reject(outcome.error);
+ }
+ return new Promise((resolve, reject) => {
+ this.#waiter = { resolve, reject };
+ });
+ }
+
+ #push(event: AmspEvent): void {
+ if (this.#waiter !== null) {
+ this.#waiter.resolve({ value: event, done: false });
+ this.#waiter = null;
+ } else {
+ this.#queue?.push(event);
+ }
+ }
+
+ #end(outcome: Outcome): void {
+ this.#outcome = outcome;
+ if (!outcome.ok) this.#rejectSession(outcome.error);
+ const waiter = this.#waiter;
+ if (waiter === null) return;
+ this.#waiter = null;
+ this.#queue = null;
+ if (outcome.ok) waiter.resolve(END);
+ else waiter.reject(outcome.error);
+ }
+
+ async #drive(agentPath: string, opts: RunOptions): Promise<RunResult> {
+ const { signal } = opts;
+ const control = this.#control;
+ const forward = () => control.abort(signal!.reason);
+ if (signal?.aborted) forward();
+ else signal?.addEventListener("abort", forward, { once: true });
+ const collector = new RunCollector();
+ try {
+ const request: RunRequest = {
+ ...(opts.sessionId !== undefined ? { session_id: opts.sessionId } : {}),
+ input: opts.input,
+ };
+ const response = await this.#transport.send("POST", `${agentPath}/runs`, {
+ body: request,
+ accept: "text/event-stream",
+ signal: control.signal,
+ });
+ const contentType = response.headers.get("content-type") ?? "";
+ if (response.body === null || !/^text\/event-stream\b/i.test(contentType)) {
+ throw new AmspStreamError(
+ `Expected an event stream, got ${contentType || "a response without a content type"}.`,
+ );
+ }
+ try {
+ for await (const data of sseData(response.body, control.signal)) {
+ if (data === "[DONE]") break;
+ const event = parseEvent(data);
+ collector.add(event);
+ if (event.type === "run.started") this.#resolveSession(event.session_id);
+ else if (event.type === "approval.requested") this.#answer(event, opts.onApproval);
+ this.#push(event);
+ }
+ } catch (err) {
+ if (control.signal.aborted) throw control.signal.reason;
+ // After run.done the outcome is known, whatever happens to the rest of the body.
+ if (!collector.finished) {
+ throw err instanceof AmspStreamError
+ ? err
+ : new AmspStreamError(`The stream broke before run.done: ${String(err)}`, {
+ cause: err,
+ });
+ }
+ }
+ const result = collector.result();
+ this.#end({ ok: true });
+ return result;
+ } catch (error) {
+ this.#end({ ok: false, error });
+ throw error;
+ } finally {
+ signal?.removeEventListener("abort", forward);
+ }
+ }
+
+ /**
+ * Answers one approval request: the callback's decision, else `deny`. The request being gone by
+ * then (someone answered first in the Web App, or the run ended) is not a failure. Any other
+ * failure to answer would leave the run waiting for good, so it ends a live run: the connection
+ * closes, the server aborts the run, and the run rejects with that error.
+ */
+ #answer(event: ApprovalRequested, onApproval: RunOptions["onApproval"]): void {
+ void (async () => {
+ const sessionId = await this.session;
+ let decision: ApprovalRequest["decision"] = "deny";
+ if (onApproval) {
+ try {
+ decision = (await onApproval(event, { sessionId })) === "allow" ? "allow" : "deny";
+ } catch {
+ decision = "deny";
+ }
+ }
+ try {
+ await this.#transport.send("POST", approvalPath(sessionId, event.tool_call.tool_call_id), {
+ body: { decision } satisfies ApprovalRequest,
+ signal: this.#control.signal,
+ });
+ } catch (err) {
+ if (err instanceof AmspHttpError && err.code === "approval_not_found") return;
+ this.#control.abort(err);
+ }
+ })().catch(() => {});
+ }
+}
+
+/**
+ * A client of one Agent's API.
+ *
+ * ```ts
+ * const client = new AgentClient({ baseUrl: "http://localhost:7364/api/amsp/v1", agent: "demo/coder", apiKey });
+ * const { text, sessionId } = await client.ask({ input: "Summarize README.md" });
+ * ```
+ */
+export class AgentClient {
+ readonly #transport: Transport;
+ readonly #agentPath: string;
+
+ constructor(opts: AgentClientOptions) {
+ const [projectId, agentId, ...rest] = opts.agent.split("/");
+ if (!projectId || !agentId || rest.length > 0) {
+ throw new TypeError(
+ `agent must be "<projectId>/<agentId>", got ${JSON.stringify(opts.agent)}.`,
+ );
+ }
+ this.#transport = new Transport(opts);
+ this.#agentPath = `/agents/${encodeURIComponent(projectId)}/${encodeURIComponent(agentId)}`;
+ }
+
+ /** Starts a run and streams it; see {@link Run}. */
+ run(opts: RunOptions): Run {
+ return new AgentRun(this.#transport, this.#agentPath, opts, true);
+ }
+
+ /** Runs to the end and returns the result; nothing is kept for iteration. */
+ ask(opts: RunOptions): Promise<RunResult> {
+ return new AgentRun(this.#transport, this.#agentPath, opts, false).result();
+ }
+
+ /** The Agent's id, name and description. */
+ async agent(): Promise<AgentInfo> {
+ const response = await this.#transport.send("GET", this.#agentPath);
+ return ((await response.json()) as AgentResponse).agent;
+ }
+
+ /** One of the Agent's API Sessions: its status and model. */
+ async session(sessionId: string): Promise<SessionInfo> {
+ const response = await this.#transport.send("GET", sessionPath(sessionId));
+ return ((await response.json()) as SessionResponse).session;
+ }
+
+ /** Aborts the Session's running run; `false` when nothing was running. */
+ async abort(sessionId: string): Promise<boolean> {
+ const response = await this.#transport.send("POST", `${sessionPath(sessionId)}/abort`);
+ return response.status === 202;
+ }
+
+ /** Answers a pending approval; an {@link AmspHttpError} `approval_not_found` when it was already decided. */
+ async approve(sessionId: string, toolCallId: string, decision: "allow" | "deny"): Promise<void> {
+ await this.#transport.send("POST", approvalPath(sessionId, toolCallId), {
+ body: { decision } satisfies ApprovalRequest,
+ });
+ }
+}
diff --git a/packages/amsp/src/collect.ts b/packages/amsp/src/collect.ts
new file mode 100644
index 00000000..0868575a
--- /dev/null
+++ b/packages/amsp/src/collect.ts
@@ -0,0 +1,113 @@
+/**
+ * What a run comes to once its stream has ended: the outcome `run.done` reports, the complete
+ * items, and the answer as text.
+ */
+import { AmspStreamError } from "./errors.js";
+import type {
+ AmspError,
+ AmspEvent,
+ ApprovalRequested,
+ RunDone,
+ StopReason,
+ TokenCounts,
+ ToolCallDone,
+} from "./types.js";
+
+/** A finished run, as `Run.result()` and `AgentClient.ask()` return it. */
+export interface RunResult {
+ /** `run.done.status`: `completed`, or how the run stopped. */
+ status: StopReason;
+ /** `run.done.error`, when the run did not complete. */
+ error?: AmspError;
+ /** The Session the run ran on; pass it as `sessionId` to continue the conversation. */
+ sessionId: string;
+ /** The main Session's assistant `text.done` items, joined with a blank line. */
+ text: string;
+ /**
+ * Every event but the `.delta` fragments, in stream order: complete items and run, request,
+ * approval and compaction events alike. A compaction summary the engine streamed has no
+ * `summary.done` and so leaves no item here; the fragments are never rebuilt into one.
+ */
+ items: AmspEvent[];
+ /** `run.done.usage`: the tokens every Request of this run counted. */
+ usage: TokenCounts;
+ /** `run.done.session_usage`: the Session's cumulative count; null when the engine reported none. */
+ sessionUsage: TokenCounts | null;
+ /** `run.done.requests`: model Requests this run issued, retried attempts included. */
+ requests: number;
+}
+
+/**
+ * Folds a run's events, in stream order, into its {@link RunResult}. `AgentClient` uses it; a
+ * program that reads a run's body itself — with its own `fetch`, its own credentials, its own
+ * URL — feeds it what `readSse` yields, parsed, and gets the same result.
+ */
+export class RunCollector {
+ #sessionId: string | null = null;
+ #done: RunDone | null = null;
+ readonly #texts: string[] = [];
+ readonly #items: AmspEvent[] = [];
+
+ add(event: AmspEvent): void {
+ if (event.type.endsWith(".delta")) return;
+ this.#items.push(event);
+ if (event.type === "run.started") {
+ this.#sessionId ??= event.session_id;
+ } else if (event.type === "run.done") {
+ this.#done ??= event;
+ } else if (
+ event.type === "text.done" &&
+ event.role === "assistant" &&
+ !event.origin?.length &&
+ event.text !== ""
+ ) {
+ this.#texts.push(event.text);
+ }
+ }
+
+ /** Whether `run.done` has arrived: the run's outcome is known. */
+ get finished(): boolean {
+ return this.#done !== null;
+ }
+
+ /** The result; an {@link AmspStreamError} when the stream never told how the run ended. */
+ result(): RunResult {
+ const done = this.#done;
+ if (done === null || this.#sessionId === null) {
+ throw new AmspStreamError(
+ "The stream ended before run.done: the connection broke or the server failed.",
+ );
+ }
+ return {
+ status: done.status,
+ ...(done.error ? { error: done.error } : {}),
+ sessionId: this.#sessionId,
+ text: this.#texts.join("\n\n"),
+ items: this.#items,
+ usage: done.usage,
+ sessionUsage: done.session_usage,
+ requests: done.requests,
+ };
+ }
+}
+
+/**
+ * A tool call's arguments as an object. AMSP carries them as a JSON string: for a completed call
+ * the engine's serialization of the parsed arguments, which the streamed fragments need not match
+ * character for character but parse to the same object; for a call cut short, the text received
+ * so far. An empty string is a call without arguments (`{}`), and anything that does not parse to
+ * a JSON object is `null`.
+ */
+export function parseArguments(
+ item: ToolCallDone | ApprovalRequested["tool_call"],
+): Record<string, unknown> | null {
+ if (item.arguments.trim() === "") return {};
+ try {
+ const parsed: unknown = JSON.parse(item.arguments);
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)
+ ? (parsed as Record<string, unknown>)
+ : null;
+ } catch {
+ return null;
+ }
+}
diff --git a/packages/amsp/src/errors.ts b/packages/amsp/src/errors.ts
new file mode 100644
index 00000000..b5bc0f2e
--- /dev/null
+++ b/packages/amsp/src/errors.ts
@@ -0,0 +1,63 @@
+/**
+ * The two ways a call can fail besides the transport itself (a network failure or an abort
+ * surfaces as `fetch` raised it): the server refused the request before any stream began, or the
+ * stream it began broke the protocol.
+ */
+
+/**
+ * A refusal before the stream: the server answered with an error status and AMSP's error
+ * envelope, `{"error": {"code": "<snake_case>", "message": "<text>"}}`.
+ */
+export class AmspHttpError extends Error {
+ /** The HTTP status, such as `401`, `404` or `409`. */
+ readonly status: number;
+ /** The envelope's stable snake_case code; `http_error` when the body was not the envelope. */
+ readonly code: string;
+
+ constructor(status: number, code: string, message: string) {
+ super(message);
+ this.name = "AmspHttpError";
+ this.status = status;
+ this.code = code;
+ }
+}
+
+/**
+ * The stream ended or broke before `run.done`, or carried a block that is not an AMSP event: the
+ * connection failed or the server did. The run's outcome is unknown; read the Session to learn
+ * what happened to it.
+ */
+export class AmspStreamError extends Error {
+ constructor(message: string, options?: { cause?: unknown }) {
+ super(message, options);
+ this.name = "AmspStreamError";
+ }
+}
+
+/**
+ * The AmspHttpError an error response stands for: its envelope's code and message, or, for a
+ * body that is not the envelope (a proxy's page, a different server), its status and the start
+ * of its text.
+ */
+export async function httpError(response: Response): Promise<AmspHttpError> {
+ const text = await response.text().catch(() => "");
+ let error: unknown;
+ try {
+ error = (JSON.parse(text) as { error?: unknown } | null)?.error;
+ } catch {
+ error = undefined;
+ }
+ const { code, message } = (error ?? {}) as { code?: unknown; message?: unknown };
+ if (typeof code === "string") {
+ return new AmspHttpError(
+ response.status,
+ code,
+ typeof message === "string" && message !== "" ? message : code,
+ );
+ }
+ return new AmspHttpError(
+ response.status,
+ "http_error",
+ `HTTP ${response.status}: ${text.slice(0, 200)}`,
+ );
+}
diff --git a/packages/amsp/src/index.ts b/packages/amsp/src/index.ts
new file mode 100644
index 00000000..825ffaec
--- /dev/null
+++ b/packages/amsp/src/index.ts
@@ -0,0 +1,11 @@
+/**
+ * @lmliheng/amsp — public entry point: the AMSP wire types, which the Adelie server
+ * imports as types too, and a zero-dependency client of one Agent's API.
+ */
+export * from "./types.js";
+export { AmspHttpError, AmspStreamError } from "./errors.js";
+export { AgentClient } from "./client.js";
+export type { AgentClientOptions, Run, RunOptions } from "./client.js";
+export { parseArguments, RunCollector } from "./collect.js";
+export type { RunResult } from "./collect.js";
+export { readSse } from "./sse.js";
diff --git a/packages/amsp/src/sse.ts b/packages/amsp/src/sse.ts
new file mode 100644
index 00000000..238545b0
--- /dev/null
+++ b/packages/amsp/src/sse.ts
@@ -0,0 +1,96 @@
+/**
+ * Server-sent events, read the way an `EventSource` reads them, for a body `fetch` returned (an
+ * `EventSource` cannot send an `Authorization` header or a POST body).
+ */
+
+/**
+ * The data of each event in an SSE body, in order: the event's `data:` lines joined with `\n`.
+ *
+ * Lines may end in LF, CRLF or a lone CR, and a chunk may split a line, a line ending or a UTF-8
+ * character anywhere. An event is dispatched at the blank line that closes it; one the body ends
+ * in the middle of is dropped, since its data may be cut short. Comment lines (`: keep-alive`)
+ * and every field but `data` are skipped. The body is read to its end, or cancelled — the
+ * connection closed — when the caller stops iterating early.
+ *
+ * `[DONE]` is AMSP's end-of-stream marker; it is yielded like any other data, so a caller stops
+ * there.
+ */
+export function readSse(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {
+ return sseData(body);
+}
+
+/**
+ * {@link readSse}, cancellable: once `signal` aborts, the body is cancelled and the read rejects
+ * with the signal's reason, whether or not the `fetch` that produced the body honours the signal
+ * itself.
+ */
+export async function* sseData(
+ body: ReadableStream<Uint8Array>,
+ signal?: AbortSignal,
+): AsyncGenerator<string> {
+ const reader = body.getReader();
+ const onAbort = () => {
+ reader.cancel(signal!.reason).catch(() => {});
+ };
+ if (signal?.aborted) onAbort();
+ else signal?.addEventListener("abort", onAbort, { once: true });
+ const decoder = new TextDecoder();
+ // One instance per body: the search position lives on the regex, and this generator yields
+ // between searches while another body's reader may run.
+ const terminator = /\r\n|\r|\n/g;
+ // Text after the last complete line; terminators are searched for from `from` on.
+ let pending = "";
+ let from = 0;
+ // The current event's data lines; null until the event has one.
+ let data: string[] | null = null;
+ try {
+ for (;;) {
+ let chunk: ReadableStreamReadResult<Uint8Array>;
+ try {
+ chunk = await reader.read();
+ } catch (err) {
+ throw signal?.aborted ? signal.reason : err;
+ }
+ if (signal?.aborted) throw signal.reason;
+ const done = chunk.done;
+ pending += done ? decoder.decode() : decoder.decode(chunk.value, { stream: true });
+
+ const lines: string[] = [];
+ let start = 0;
+ let waitForLf = false;
+ terminator.lastIndex = from;
+ for (let match = terminator.exec(pending); match; match = terminator.exec(pending)) {
+ // A CR that ends what has arrived may be the first half of a CRLF.
+ if (!done && match[0] === "\r" && match.index === pending.length - 1) {
+ waitForLf = true;
+ break;
+ }
+ lines.push(pending.slice(start, match.index));
+ start = match.index + match[0].length;
+ }
+ pending = pending.slice(start);
+ from = waitForLf ? pending.length - 1 : pending.length;
+
+ for (const line of lines) {
+ if (line === "") {
+ if (data !== null) {
+ const event = data.join("\n");
+ data = null;
+ yield event;
+ }
+ continue;
+ }
+ // A comment has an empty field name, so it falls out with every other non-data field.
+ const colon = line.indexOf(":");
+ if ((colon === -1 ? line : line.slice(0, colon)) !== "data") continue;
+ const value = colon === -1 ? "" : line.slice(colon + 1);
+ (data ??= []).push(value.startsWith(" ") ? value.slice(1) : value);
+ }
+ if (done) return;
+ }
+ } finally {
+ signal?.removeEventListener("abort", onAbort);
+ // Closes the connection when the caller stopped early or the read failed; a no-op at the end.
+ await reader.cancel().catch(() => {});
+ }
+}
diff --git a/packages/amsp/src/types.ts b/packages/amsp/src/types.ts
new file mode 100644
index 00000000..4e90c3a7
--- /dev/null
+++ b/packages/amsp/src/types.ts
@@ -0,0 +1,330 @@
+/**
+ * AMSP (Agent Message Stream Protocol): the wire types.
+ *
+ * MMSP streams one model call; AMSP streams one run of an Agent — one Task — on a Session the
+ * caller continues by id. A run is a `text/event-stream` of `data: <JSON>` blocks, one event
+ * each, closed by `data: [DONE]`:
+ *
+ * stream := run.started body* run.done
+ * request := request.started (item | tool_result | approval | hook.fired)* request.done
+ * item := K.delta* K.done ; K = thinking | text | tool_call | inline_data | inline_thinking
+ *
+ * Events are flat objects discriminated by `type`, snake_case on the wire like MMSP and the
+ * OmniMessage payloads they are projected from. `run.done` is the one terminal event and always
+ * arrives, errors included. Clients must ignore a `type` they do not know: new event types and
+ * optional fields are additive within `/v1`; a change to an existing field's meaning is `/v2`.
+ *
+ * A Request pair brackets the model's output, not the tools: the engine runs a tool as soon as
+ * its call is complete, so the approval and the start of the result arrive while the Request is
+ * still open, and the result may end after `request.done` (always before the next
+ * `request.started` of the same origin). Attribute results by `tool_call_id`. Fragments and
+ * complete items are forwarded as the engine produced them and never rebuilt from each other.
+ *
+ * The server's translator produces these events and imports this file as types; the client
+ * consumes them.
+ */
+
+// ---- vocabulary shared with OmniMessage (same strings, same meaning) ----
+export type StopReason = "completed" | "aborted" | "retryable" | "fatal";
+export type Role = "user" | "assistant";
+export type ApprovalDecision = "allow" | "deny" | "forbidden";
+export type Sender = "user" | "parent_agent" | "harness" | "server";
+export type CompactionReason = "context" | "turns" | "manual";
+export type CompactionMode = "summarize" | "discard";
+export type HookPoint = "stop" | "pre_tool_use" | "user_prompt";
+export type HookDecision = "continue" | "stop" | "allow" | "deny";
+export type SessionStatus = "idle" | "running" | "compacting";
+
+export interface TokenCounts {
+ cache_read: number;
+ cache_write: number;
+ output: number;
+ total: number;
+}
+/** The one error shape: `code` snake_case and stable (OmniMessage ErrorCode values plus AMSP's own, listed in the protocol reference); `message` raw text. */
+export interface AmspError {
+ code: string;
+ message: string;
+}
+export interface ToolDefinition {
+ name: string;
+ description: string;
+ parameters?: Record<string, unknown>;
+}
+export interface McpServerResult {
+ server: string;
+ transport: "stdio" | "http" | "sse";
+ status: StopReason;
+ duration_ms: number;
+ tools?: number;
+ error?: AmspError;
+}
+
+interface Base {
+ /** ISO 8601 UTC. */
+ at: string;
+ /** Child-Session chain, outer→inner (OmniMessage `origin`); absent = the main Session. */
+ origin?: string[];
+}
+
+// ---- run layer ----
+export interface RunStarted extends Base {
+ type: "run.started";
+ session_id: string;
+ agent: string /* "<projectId>/<agentId>" */;
+}
+export interface RunDone extends Base {
+ type: "run.done";
+ status: StopReason;
+ error?: AmspError;
+ /** Model Requests this run issued (attempts included). */
+ requests: number;
+ usage: TokenCounts;
+ session_usage: TokenCounts | null;
+}
+
+// ---- context / bootstrap ----
+/**
+ * A new model context the engine streams: a child Session starting (with `origin`) or, between
+ * runs, a model switch. The context a compaction opens is recorded in the Trace, not streamed, so
+ * none follows `compaction.done`.
+ */
+export interface ContextOpened extends Base {
+ type: "context.opened";
+ session_id: string;
+ provider: string;
+ model_id: string;
+ context_window: number | "unknown";
+}
+export interface McpConnectStarted extends Base {
+ type: "mcp_connect.started";
+ servers: string[];
+}
+export interface McpConnectDone extends Base {
+ type: "mcp_connect.done";
+ status: StopReason;
+ results: McpServerResult[];
+ error?: AmspError;
+}
+export interface ToolsReady extends Base {
+ type: "tools.ready";
+ tools: ToolDefinition[];
+}
+
+// ---- request layer ----
+export interface RequestStarted extends Base {
+ type: "request.started";
+ request: number /* 1-based within the run */;
+}
+/** The Request ended. Results of the tools it called may still follow, before the next `request.started`. */
+export interface RequestDone extends Base {
+ type: "request.done";
+ request: number;
+ status: StopReason;
+ usage: TokenCounts | null;
+ error?: AmspError;
+ /** 1-based attempt ordinal; present on retries and failures (OmniMessage `attempt`). */
+ attempt?: number;
+ /** Present only when the engine will retry this failure within the run. */
+ retry_in_ms?: number;
+}
+
+// ---- item layer: fragments ----
+export interface TextDelta extends Base {
+ type: "text.delta";
+ role: "assistant";
+ text: string;
+}
+export interface ThinkingDelta extends Base {
+ type: "thinking.delta";
+ thinking: string;
+}
+export interface ToolCallDelta extends Base {
+ type: "tool_call.delta";
+ tool_call_id: string;
+ /** Set on the first fragment; may be empty afterwards. */
+ name: string;
+ /** A piece of the arguments text as the provider streamed it. */
+ arguments: string;
+}
+/** Output a running tool has produced so far; may arrive while the Request that made the call is still open. */
+export interface ToolResultDelta extends Base {
+ type: "tool_result.delta";
+ tool_call_id: string;
+ output: string;
+ /** Not incremental: one fragment carries the whole set. */
+ images?: string[];
+}
+/**
+ * A fragment of a compaction's summary. A streamed summary has no `summary.done`: the engine
+ * streams the fragments or delivers the text whole, never both, and nothing rebuilds one from the
+ * other.
+ */
+export interface SummaryDelta extends Base {
+ type: "summary.delta";
+ text: string;
+}
+
+// ---- item layer: complete items ----
+export interface TextDone extends Base {
+ type: "text.done";
+ role: Role;
+ text: string;
+ stop_reason: StopReason;
+ /** On user-role texts the harness injected mid-run. */
+ sender?: Sender;
+}
+export interface ThinkingDone extends Base {
+ type: "thinking.done";
+ thinking: string;
+ stop_reason: StopReason;
+}
+export interface ToolCallDone extends Base {
+ type: "tool_call.done";
+ tool_call_id: string;
+ name: string;
+ /**
+ * The complete arguments as a JSON string: the engine's serialization of the parsed call, which
+ * the fragments joined need not equal character for character (`{"command": "ls"}` streamed,
+ * `{"command":"ls"}` here) but parse to the same object; parse with `parseArguments`. A call cut
+ * short (`stop_reason` other than `completed`) carries the text received so far instead.
+ */
+ arguments: string;
+ stop_reason: StopReason;
+}
+/** The tool's result as the model receives it; may arrive after the call's `request.done`, always before the next `request.started` of the same origin. */
+export interface ToolResultDone extends Base {
+ type: "tool_result.done";
+ tool_call_id: string;
+ output: string;
+ images?: string[];
+ stop_reason: StopReason;
+}
+export interface InlineDataDone extends Base {
+ type: "inline_data.done";
+ role: Role;
+ mime_type: string;
+ /** base64 */
+ data: string;
+ stop_reason: StopReason;
+}
+export interface InlineThinkingDone extends Base {
+ type: "inline_thinking.done";
+ mime_type: string;
+ data: string;
+ stop_reason: StopReason;
+}
+export interface ImageUrlDone extends Base {
+ type: "image_url.done";
+ role: "user";
+ image_url: string;
+}
+/** A compaction's summary delivered whole; absent when the summary was streamed. */
+export interface SummaryDone extends Base {
+ type: "summary.done";
+ text: string;
+ stop_reason: StopReason;
+}
+
+// ---- approvals ----
+/** A tool call waiting for the caller's answer; arrives while the call's Request is still open and carries the whole call. */
+export interface ApprovalRequested extends Base {
+ type: "approval.requested";
+ tool_call: { tool_call_id: string; name: string; arguments: string };
+}
+export interface ApprovalDecided extends Base {
+ type: "approval.decided";
+ tool_call_id: string;
+ decision: ApprovalDecision;
+}
+
+// ---- compaction ----
+export interface CompactionStarted extends Base {
+ type: "compaction.started";
+ reason: CompactionReason;
+ mode: CompactionMode;
+ context: number;
+ turns: number;
+}
+export interface CompactionDone extends Base {
+ type: "compaction.done";
+ reason: CompactionReason;
+ mode: CompactionMode;
+ status: StopReason;
+ usage: TokenCounts | null;
+ error?: AmspError;
+ attempt?: number;
+}
+
+// ---- hooks ----
+export interface HookFired extends Base {
+ type: "hook.fired";
+ hook: HookPoint;
+ name: string;
+ decision?: HookDecision;
+ reason?: string;
+ output?: Record<string, string | number | boolean>;
+}
+
+export type AmspEvent =
+ | RunStarted
+ | RunDone
+ | ContextOpened
+ | McpConnectStarted
+ | McpConnectDone
+ | ToolsReady
+ | RequestStarted
+ | RequestDone
+ | TextDelta
+ | ThinkingDelta
+ | ToolCallDelta
+ | ToolResultDelta
+ | SummaryDelta
+ | TextDone
+ | ThinkingDone
+ | ToolCallDone
+ | ToolResultDone
+ | InlineDataDone
+ | InlineThinkingDone
+ | ImageUrlDone
+ | SummaryDone
+ | ApprovalRequested
+ | ApprovalDecided
+ | CompactionStarted
+ | CompactionDone
+ | HookFired;
+
+// ---- requests / responses ----
+export type InputItem =
+ | { type: "text"; text: string }
+ | { type: "image_url"; image_url: string /* data: URL or http(s) URL */ };
+export interface RunRequest {
+ session_id?: string;
+ input: string | InputItem[];
+}
+export interface AgentInfo {
+ id: string /* "<projectId>/<agentId>" */;
+ name?: string;
+ description?: string;
+}
+export interface AgentResponse {
+ agent: AgentInfo;
+}
+export interface SessionInfo {
+ id: string;
+ agent: string;
+ status: SessionStatus;
+ provider: string;
+ model_id: string;
+ created_at: string;
+ last_active_at: string;
+}
+export interface SessionResponse {
+ session: SessionInfo;
+}
+export interface ApprovalRequest {
+ decision: "allow" | "deny";
+}
+export interface ErrorResponse {
+ error: AmspError;
+}
diff --git a/packages/amsp/test/client.test.ts b/packages/amsp/test/client.test.ts
new file mode 100644
index 00000000..85951747
--- /dev/null
+++ b/packages/amsp/test/client.test.ts
@@ -0,0 +1,868 @@
+/**
+ * AgentClient against a scripted AMSP server (the package's one fetch fake).
+ *
+ * Runs and their streams
+ * - Iterating a run yields the server's events in order and stops at [DONE]: nothing after it is
+ * read, and the connection is closed.
+ * - A run POSTs its input, and the Session to continue, as JSON to the Agent's runs route, with
+ * the key as a Bearer token and the caller's extra headers; a keyless client sends no
+ * Authorization.
+ * - result() joins the main Session's assistant texts and keeps every complete item, on the order
+ * the server captured: user texts, a subagent's texts and compaction summaries stay out of the
+ * text; a summary the engine streamed has no summary.done and leaves no item (fragments are
+ * never rebuilt into one), one delivered whole is kept as its summary.done.
+ * - A run that ends fatal resolves with that status and error; it does not reject.
+ * - session resolves from run.started while the server still holds back the first content event.
+ * - Keep-alive comments, CRLF framing, chunks split mid-event and a data block spread over two
+ * lines leave the events intact.
+ * - An event type the client does not know reaches the iterator and the items.
+ * - Leaving the loop early stops the iteration, not the run: the connection stays open and
+ * result() still resolves.
+ * - Events are kept for an iteration that starts after the run ended, and a finished iteration
+ * keeps answering done.
+ * - A run's events can be iterated once.
+ *
+ * Failures
+ * - A refusal before the stream rejects the run, its session and its iteration with an
+ * AmspHttpError carrying the status and the envelope's code; a body that is not the envelope
+ * reads as `http_error` with the start of the body.
+ * - A stream that ends, says [DONE] or breaks before run.done is an AmspStreamError, raised by
+ * the iteration after the events that did arrive; one that ends or breaks after run.done still
+ * resolves.
+ * - A 200 answer that is not an event stream (saying what came instead), and a block that is not
+ * an AMSP event, are AmspStreamErrors.
+ *
+ * Approvals (on the captured order: the engine runs the tool while its Request is still open, so
+ * approval.requested, approval.decided and the first result fragment precede request.done, and
+ * the rest of the result follows it)
+ * - An approval request is answered by POST with the callback's decision, even when the caller
+ * only awaits the result; no callback, or a throwing one, answers deny.
+ * - The result of such a run carries the next Request's text and one tool_result.done for the
+ * call, whichever side of request.done its fragments fell on.
+ * - An approval someone else answered first does not fail the run, and an answer that fails after
+ * the run completed leaves it completed.
+ * - An approval the server refuses to take ends the run with that refusal and closes the
+ * connection, so the server aborts the run instead of waiting for good.
+ *
+ * Aborts
+ * - Aborting the signal mid-stream closes the connection and rejects with the signal's AbortError,
+ * whether the fetch errors the body itself or leaves it to the reader.
+ * - The iteration stops at once when the signal aborts, and events not yet read are dropped.
+ * - A signal that aborts as the response arrives rejects without waiting for the stream; one
+ * aborted before the run sends nothing.
+ * - run.abort() asks the server to abort and the stream ends with run.done aborted; on a run that
+ * is over, or was refused, it sends nothing.
+ *
+ * The rest of the surface
+ * - agent() and session() read the Agent and one of its Sessions; an unknown Session is an
+ * AmspHttpError.
+ * - abort(sessionId) says whether a run was interrupted; approve() posts a decision and reports
+ * one already taken as approval_not_found.
+ * - parseArguments returns the arguments object, {} for none, and null for anything malformed;
+ * a tool_call.done's arguments (the engine's serialization of the parsed call) and its
+ * fragments joined (the provider's text) parse to the same object although their text differs.
+ * - An agent reference that is not <projectId>/<agentId> is refused at construction.
+ * - A fetch handed to the client carries its requests instead of the global one.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ AgentClient,
+ AmspHttpError,
+ AmspStreamError,
+ parseArguments,
+ type AmspEvent,
+ type RunOptions,
+} from "../src/index.js";
+import {
+ BASE_URL,
+ DONE,
+ createFetchFake,
+ frame,
+ gate,
+ never,
+ type FetchFake,
+ type Step,
+} from "./helpers/fetch-fake.js";
+import { APPROVAL_ROUND_TRIP, MIXED_RUN, sessionOf } from "./helpers/streams.js";
+
+const AT = "2026-10-07T10:00:00.000Z";
+const SESSION = "session-2026-10-07-10-00-00-3f9a1c2e";
+const KEY = "test-agent-key";
+const RUNS = "/agents/demo/coder/runs";
+const APPROVAL = `/sessions/${SESSION}/approvals/call_1`;
+const USAGE = { cache_read: 0, cache_write: 0, output: 2, total: 412 };
+
+/** The approval route of the captured round trip's Session. */
+const ROUND_TRIP_SESSION = sessionOf(APPROVAL_ROUND_TRIP);
+const ROUND_TRIP_APPROVAL = `/sessions/${ROUND_TRIP_SESSION}/approvals/call_1`;
+const ROUND_TRIP_REQUESTED = APPROVAL_ROUND_TRIP.find((e) => e.type === "approval.requested")!;
+
+function ev(type: string, fields: Record<string, unknown> = {}): AmspEvent {
+ return { type, at: AT, ...fields } as AmspEvent;
+}
+
+const started = ev("run.started", { session_id: SESSION, agent: "demo/coder" });
+const runDone = (fields: Record<string, unknown> = {}) =>
+ ev("run.done", {
+ status: "completed",
+ requests: 1,
+ usage: USAGE,
+ session_usage: USAGE,
+ ...fields,
+ });
+
+/** A plain answer, as the protocol reference shows it. */
+const PLAIN = [
+ started,
+ ev("request.started", { request: 1 }),
+ ev("text.delta", { role: "assistant", text: "" }),
+ ev("text.delta", { role: "assistant", text: "Hello" }),
+ ev("text.delta", { role: "assistant", text: "!" }),
+ ev("text.done", { role: "assistant", text: "Hello!", stop_reason: "completed" }),
+ ev("request.done", { request: 1, status: "completed", usage: USAGE }),
+ runDone(),
+];
+
+const APPROVAL_REQUESTED = ev("approval.requested", {
+ tool_call: { tool_call_id: "call_1", name: "exec_command", arguments: '{"command":"ls"}' },
+});
+
+/**
+ * The captured round trip: the server holds the stream at approval.requested until `answered`
+ * settles, then the tool runs — its decision and first result fragment before request.done, the
+ * rest of the result after it, then the second Request.
+ */
+function approvalScript(answered: Promise<unknown>): Step[] {
+ const asked = APPROVAL_ROUND_TRIP.indexOf(ROUND_TRIP_REQUESTED) + 1;
+ return [
+ ...APPROVAL_ROUND_TRIP.slice(0, asked).map(frame),
+ answered,
+ ...APPROVAL_ROUND_TRIP.slice(asked).map(frame),
+ DONE,
+ ];
+}
+
+async function collect(run: AsyncIterable<AmspEvent>): Promise<AmspEvent[]> {
+ const events: AmspEvent[] = [];
+ for await (const event of run) events.push(event);
+ return events;
+}
+
+let fake: FetchFake;
+let client: AgentClient;
+
+beforeEach(() => {
+ fake = createFetchFake();
+ vi.stubGlobal("fetch", fake.fetch);
+ client = new AgentClient({ baseUrl: BASE_URL, agent: "demo/coder", apiKey: KEY });
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("a run's stream", () => {
+ it("yields the server's events in order and stops at [DONE]", async () => {
+ const served = fake.stream("POST", RUNS, [
+ ...PLAIN.map(frame),
+ DONE,
+ frame(ev("text.done", { role: "assistant", text: "after the end" })),
+ ]);
+
+ expect(await collect(client.run({ input: "hi" }))).toEqual(PLAIN);
+ expect(served.closed).toBe(true);
+ });
+
+ it("posts the input and the Session to continue to the Agent's runs route, with the key and the caller's headers", async () => {
+ client = new AgentClient({
+ baseUrl: `${BASE_URL}/`,
+ agent: "demo/coder",
+ apiKey: KEY,
+ headers: { "X-Request-Source": "nightly-report" },
+ });
+ fake.stream("POST", RUNS, [...PLAIN.map(frame), DONE]);
+ const input: RunOptions["input"] = [
+ { type: "text", text: "What is in this picture?" },
+ { type: "image_url", image_url: "data:image/png;base64,iVBORw0KGgo=" },
+ ];
+
+ await client.ask({ sessionId: SESSION, input });
+
+ expect(fake.calls).toHaveLength(1);
+ const [call] = fake.calls;
+ expect(call).toMatchObject({
+ method: "POST",
+ path: RUNS,
+ body: { session_id: SESSION, input },
+ });
+ expect(call!.headers.get("authorization")).toBe(`Bearer ${KEY}`);
+ expect(call!.headers.get("content-type")).toBe("application/json");
+ expect(call!.headers.get("accept")).toBe("text/event-stream");
+ expect(call!.headers.get("x-request-source")).toBe("nightly-report");
+ });
+
+ it("sends no Authorization from a keyless client", async () => {
+ client = new AgentClient({ baseUrl: BASE_URL, agent: "demo/coder" });
+ fake.stream("POST", RUNS, [...PLAIN.map(frame), DONE]);
+
+ await client.ask({ input: "hi" });
+
+ expect(fake.calls[0]!.headers.has("authorization")).toBe(false);
+ expect(fake.calls[0]!.body).toEqual({ input: "hi" });
+ });
+
+ it("joins the main Session's assistant texts in result(), leaving deltas, user texts, a subagent's texts and a streamed summary out", async () => {
+ fake.stream("POST", RUNS, [...MIXED_RUN.map(frame), DONE]);
+
+ const result = await client.ask({ input: "Fix the build" });
+
+ expect(result).toMatchObject({
+ status: "completed",
+ sessionId: sessionOf(MIXED_RUN),
+ text: "Working on it.\n\nDone: the build is green.",
+ usage: { output: 18, total: 1100 },
+ sessionUsage: { output: 15, total: 900 },
+ requests: 3,
+ });
+ expect(result).not.toHaveProperty("error");
+ expect(result.items.map((item) => item.type)).toEqual([
+ "run.started",
+ "request.started",
+ "text.done",
+ "request.done",
+ "text.done", // the steering text, role user
+ "context.opened", // the subagent's Session
+ "request.started",
+ "text.done",
+ "request.done",
+ "compaction.started",
+ "compaction.done", // the summary was streamed: no summary.done, and none is rebuilt
+ "request.started",
+ "text.done",
+ "request.done",
+ "run.done",
+ ]);
+ expect(result.items.find((item) => item.type === "context.opened")).toMatchObject({
+ origin: ["session-2026-10-07-10-00-01-c0000001"],
+ });
+ });
+
+ it("keeps a summary the engine delivered whole as its summary.done item, still out of the text", async () => {
+ const summary = ev("summary.done", { text: "The whole summary.", stop_reason: "completed" });
+ fake.stream("POST", RUNS, [
+ frame(started),
+ frame(ev("request.started", { request: 1 })),
+ frame(ev("text.done", { role: "assistant", text: "Before.", stop_reason: "completed" })),
+ frame(ev("request.done", { request: 1, status: "completed", usage: USAGE })),
+ frame(
+ ev("compaction.started", { reason: "manual", mode: "summarize", context: 10, turns: 1 }),
+ ),
+ frame(summary),
+ frame(ev("compaction.done", { reason: "manual", mode: "summarize", status: "completed" })),
+ frame(runDone()),
+ DONE,
+ ]);
+
+ const result = await client.ask({ input: "hi" });
+
+ expect(result.text).toBe("Before.");
+ expect(result.items.filter((item) => item.type.startsWith("summary."))).toEqual([summary]);
+ });
+
+ it("resolves a run that ended fatal with its status and error", async () => {
+ const error = { code: "auth", message: "401 invalid x-api-key" };
+ fake.stream("POST", RUNS, [
+ frame(started),
+ frame(ev("request.started", { request: 1 })),
+ frame(ev("request.done", { request: 1, status: "fatal", usage: null, error, attempt: 1 })),
+ frame(runDone({ status: "fatal", error })),
+ DONE,
+ ]);
+
+ await expect(client.ask({ input: "hi" })).resolves.toMatchObject({
+ status: "fatal",
+ error,
+ text: "",
+ });
+ });
+
+ it("resolves the session from run.started while the server holds back the first content event", async () => {
+ const hold = gate();
+ fake.stream("POST", RUNS, [frame(started), hold.promise, ...PLAIN.slice(1).map(frame), DONE]);
+
+ const run = client.run({ input: "hi" });
+
+ await expect(run.session).resolves.toBe(SESSION);
+ hold.open();
+ await expect(run.result()).resolves.toMatchObject({ sessionId: SESSION, text: "Hello!" });
+ });
+
+ it("reads events through keep-alive comments, CRLF framing, split chunks and a two-line data block", async () => {
+ const twoLines =
+ 'data: {"type":"text.done","at":"2026-10-07T10:00:00.000Z",\r\ndata: "role":"assistant","text":"Hello!","stop_reason":"completed"}\r\n\r\n';
+ const wire = [
+ frame(started),
+ ": keep-alive\n\n",
+ frame(ev("request.started", { request: 1 })),
+ twoLines,
+ ": keep-alive\n\n",
+ frame(runDone()),
+ DONE,
+ ]
+ .join("")
+ .replaceAll(/(?<!\r)\n/g, "\r\n");
+ const chunks = wire.match(/[\s\S]{1,7}/g)!;
+ fake.stream("POST", RUNS, chunks);
+
+ const events = await collect(client.run({ input: "hi" }));
+
+ expect(events.map((event) => event.type)).toEqual([
+ "run.started",
+ "request.started",
+ "text.done",
+ "run.done",
+ ]);
+ expect(events[2]).toMatchObject({ role: "assistant", text: "Hello!" });
+ });
+
+ it("passes an event type it does not know to the iterator and the items", async () => {
+ const unknown = ev("plan.updated", { steps: ["read", "summarize"] });
+ fake.stream("POST", RUNS, [frame(started), frame(unknown), frame(runDone()), DONE]);
+ const run = client.run({ input: "hi" });
+
+ expect(await collect(run)).toContainEqual(unknown);
+ expect((await run.result()).items).toContainEqual(unknown);
+ });
+
+ it("keeps the run going when the loop is left early, so result() still resolves", async () => {
+ const hold = gate();
+ const served = fake.stream("POST", RUNS, [
+ frame(started),
+ hold.promise,
+ ...PLAIN.slice(1).map(frame),
+ DONE,
+ ]);
+ const run = client.run({ input: "hi" });
+
+ for await (const event of run) {
+ expect(event.type).toBe("run.started");
+ break;
+ }
+ expect(served.closed).toBe(false);
+ hold.open();
+
+ await expect(run.result()).resolves.toMatchObject({ status: "completed", text: "Hello!" });
+ expect(fake.calls.map((call) => call.path)).toEqual([RUNS]);
+ });
+
+ it("keeps every event for an iteration that starts after the run ended", async () => {
+ fake.stream("POST", RUNS, [...PLAIN.map(frame), DONE]);
+ const run = client.run({ input: "hi" });
+
+ await run.result();
+
+ expect(await collect(run)).toEqual(PLAIN);
+ });
+
+ it("keeps answering done once the iteration has finished", async () => {
+ fake.stream("POST", RUNS, [...PLAIN.map(frame), DONE]);
+ const iterator = client.run({ input: "hi" })[Symbol.asyncIterator]();
+ while (!(await iterator.next()).done);
+
+ await expect(iterator.next()).resolves.toEqual({ value: undefined, done: true });
+ });
+
+ it("refuses to iterate a run's events twice", async () => {
+ fake.stream("POST", RUNS, [...PLAIN.map(frame), DONE]);
+ const run = client.run({ input: "hi" });
+ await collect(run);
+
+ expect(() => run[Symbol.asyncIterator]()).toThrow(TypeError);
+ });
+});
+
+describe("a run that fails", () => {
+ it.each([
+ {
+ answer: "the error envelope",
+ status: 401,
+ body: '{"error":{"code":"unauthorized","message":"This Agent requires an API key."}}',
+ expected: { status: 401, code: "unauthorized", message: "This Agent requires an API key." },
+ },
+ {
+ answer: "an envelope without a message",
+ status: 403,
+ body: '{"error":{"code":"agent_api_disabled"}}',
+ expected: { status: 403, code: "agent_api_disabled", message: "agent_api_disabled" },
+ },
+ {
+ answer: "a body that is not the envelope",
+ status: 502,
+ body: "<html>Bad Gateway</html>",
+ expected: { status: 502, code: "http_error", message: "HTTP 502: <html>Bad Gateway</html>" },
+ },
+ ])(
+ "rejects the run, its session and its iteration with an AmspHttpError read from $answer",
+ async ({ status, body, expected }) => {
+ fake.text("POST", RUNS, status, body, "application/json");
+
+ const run = client.run({ input: "hi" });
+
+ for (const outcome of [run.result(), run.session, collect(run)]) {
+ const error = await outcome.then(
+ () => null,
+ (err: unknown) => err,
+ );
+ expect(error).toBeInstanceOf(AmspHttpError);
+ expect(error).toMatchObject(expected);
+ }
+ },
+ );
+
+ it.each([
+ { how: "ends", tail: [] as Step[] },
+ { how: "says [DONE]", tail: [DONE] as Step[] },
+ { how: "breaks", tail: [{ fail: new TypeError("terminated") }] as Step[] },
+ ])(
+ "is an AmspStreamError, after the events that did arrive, when the stream $how before run.done",
+ async ({ tail }) => {
+ fake.stream("POST", RUNS, [...PLAIN.slice(0, 4).map(frame), ...tail]);
+ const run = client.run({ input: "hi" });
+
+ await expect(run.result()).rejects.toBeInstanceOf(AmspStreamError);
+ const seen: AmspEvent[] = [];
+ const iteration = (async () => {
+ for await (const event of run) seen.push(event);
+ })();
+ await expect(iteration).rejects.toBeInstanceOf(AmspStreamError);
+ expect(seen).toEqual(PLAIN.slice(0, 4));
+ },
+ );
+
+ it.each([
+ { how: "ends", tail: [] as Step[] },
+ { how: "breaks", tail: [{ fail: new TypeError("terminated") }] as Step[] },
+ ])("still resolves when the stream $how after run.done", async ({ tail }) => {
+ fake.stream("POST", RUNS, [...PLAIN.map(frame), ...tail]);
+
+ await expect(client.ask({ input: "hi" })).resolves.toMatchObject({ status: "completed" });
+ });
+
+ it.each([
+ {
+ answer: "an HTML page",
+ serve: (f: FetchFake) => f.text("POST", RUNS, 200, "<!doctype html>", "text/html"),
+ named: "text/html",
+ },
+ {
+ answer: "an empty answer",
+ serve: (f: FetchFake) => f.empty("POST", RUNS, 200),
+ named: "without a content type",
+ },
+ ])(
+ "is an AmspStreamError saying what came instead when a 200 answer is $answer",
+ async ({ serve, named }) => {
+ serve(fake);
+
+ const error = await client.ask({ input: "hi" }).catch((err: unknown) => err);
+
+ expect(error).toBeInstanceOf(AmspStreamError);
+ expect((error as Error).message).toContain(named);
+ },
+ );
+
+ it.each([
+ { block: "not JSON", data: "data: {not json\n\n" },
+ { block: "JSON without a type", data: 'data: {"session_id":"x"}\n\n' },
+ ])("is an AmspStreamError when a block is $block", async ({ data }) => {
+ const served = fake.stream("POST", RUNS, [frame(started), data, never()]);
+
+ await expect(client.ask({ input: "hi" })).rejects.toBeInstanceOf(AmspStreamError);
+ expect(served.closed).toBe(true);
+ });
+});
+
+describe("approvals", () => {
+ it.each([
+ { callback: "no callback", onApproval: undefined, decision: "deny" },
+ { callback: "a callback that allows", onApproval: () => "allow" as const, decision: "allow" },
+ {
+ callback: "an async callback that denies",
+ onApproval: async () => "deny" as const,
+ decision: "deny",
+ },
+ {
+ callback: "a callback that throws",
+ onApproval: () => {
+ throw new Error("no terminal to ask");
+ },
+ decision: "deny",
+ },
+ ])(
+ "answers with $decision for $callback, while the caller only awaits the result",
+ async ({ onApproval, decision }) => {
+ fake.empty("POST", ROUND_TRIP_APPROVAL, 204);
+ fake.stream("POST", RUNS, approvalScript(fake.requested("POST", ROUND_TRIP_APPROVAL)));
+
+ await expect(client.ask({ input: "List the files", onApproval })).resolves.toMatchObject({
+ status: "completed",
+ });
+
+ const answer = fake.calls.find((call) => call.path === ROUND_TRIP_APPROVAL)!;
+ expect(answer.body).toEqual({ decision });
+ expect(answer.headers.get("authorization")).toBe(`Bearer ${KEY}`);
+ },
+ );
+
+ it("hands the callback the request and the Session it belongs to", async () => {
+ fake.empty("POST", ROUND_TRIP_APPROVAL, 204);
+ fake.stream("POST", RUNS, approvalScript(fake.requested("POST", ROUND_TRIP_APPROVAL)));
+ const asked: unknown[] = [];
+
+ await client.ask({
+ input: "List the files",
+ onApproval: (request, ctx) => {
+ asked.push({ request, ctx });
+ return parseArguments(request.tool_call)?.command === "ls" ? "allow" : "deny";
+ },
+ });
+
+ expect(asked).toEqual([
+ { request: ROUND_TRIP_REQUESTED, ctx: { sessionId: ROUND_TRIP_SESSION } },
+ ]);
+ expect(fake.calls.find((call) => call.path === ROUND_TRIP_APPROVAL)!.body).toEqual({
+ decision: "allow",
+ });
+ });
+
+ it("collects the next Request's text and one tool_result.done for a tool that ran inside its Request", async () => {
+ fake.empty("POST", ROUND_TRIP_APPROVAL, 204);
+ fake.stream("POST", RUNS, approvalScript(fake.requested("POST", ROUND_TRIP_APPROVAL)));
+
+ const result = await client.ask({ input: "List the files", onApproval: () => "allow" });
+
+ expect(result).toMatchObject({
+ status: "completed",
+ sessionId: ROUND_TRIP_SESSION,
+ text: "Two entries: README.md and src.",
+ requests: 2,
+ });
+ // The result's fragments fell on both sides of request.done; its one .done closes it.
+ expect(result.items.map((item) => item.type)).toEqual([
+ "run.started",
+ "request.started",
+ "tool_call.done",
+ "approval.requested",
+ "approval.decided",
+ "request.done",
+ "tool_result.done",
+ "request.started",
+ "text.done",
+ "request.done",
+ "run.done",
+ ]);
+ expect(result.items.find((item) => item.type === "tool_result.done")).toMatchObject({
+ tool_call_id: "call_1",
+ output: "README.md\nsrc\n",
+ });
+ });
+
+ it("finishes the run when someone else answered the approval first", async () => {
+ fake.json("POST", ROUND_TRIP_APPROVAL, 404, {
+ error: { code: "approval_not_found", message: "This approval was already decided." },
+ });
+ fake.stream("POST", RUNS, approvalScript(fake.requested("POST", ROUND_TRIP_APPROVAL)));
+
+ await expect(
+ client.ask({ input: "List the files", onApproval: () => "allow" }),
+ ).resolves.toMatchObject({
+ status: "completed",
+ });
+ });
+
+ it("leaves a completed run as it was when an answer fails after the run ended", async () => {
+ const late = gate();
+ fake.json(
+ "POST",
+ APPROVAL,
+ 500,
+ { error: { code: "internal", message: "boom" } },
+ late.promise,
+ );
+ fake.stream("POST", RUNS, [
+ frame(started),
+ frame(APPROVAL_REQUESTED),
+ fake.requested("POST", APPROVAL),
+ frame(ev("approval.decided", { tool_call_id: "call_1", decision: "deny" })),
+ frame(runDone()),
+ DONE,
+ ]);
+ const run = client.run({ input: "list the files" });
+ await expect(run.result()).resolves.toMatchObject({ status: "completed" });
+
+ const answer = await fake.requested("POST", APPROVAL);
+ const failed = new Promise((resolve) => answer.signal!.addEventListener("abort", resolve));
+ late.open();
+ await failed;
+
+ expect((await collect(run)).map((event) => event.type)).toEqual([
+ "run.started",
+ "approval.requested",
+ "approval.decided",
+ "run.done",
+ ]);
+ });
+
+ it("ends the run with the server's refusal to take an answer, and closes the connection", async () => {
+ fake.json("POST", ROUND_TRIP_APPROVAL, 401, {
+ error: { code: "unauthorized", message: "This Agent requires an API key." },
+ });
+ const served = fake.stream("POST", RUNS, approvalScript(never()));
+
+ await expect(client.ask({ input: "List the files" })).rejects.toMatchObject({
+ status: 401,
+ code: "unauthorized",
+ });
+ expect(served.closed).toBe(true);
+ });
+});
+
+describe("aborting", () => {
+ it.each([
+ { fetch: "a fetch that errors the body on abort", abortErrorsBody: true },
+ { fetch: "a fetch that leaves the body to its reader", abortErrorsBody: false },
+ ])(
+ "closes the connection and rejects with the AbortError when the signal aborts mid-stream, through $fetch",
+ async ({ abortErrorsBody }) => {
+ const controller = new AbortController();
+ const served = fake.stream(
+ "POST",
+ RUNS,
+ [
+ ...PLAIN.slice(0, 4).map(frame),
+ () => {
+ controller.abort();
+ return never();
+ },
+ ],
+ { abortErrorsBody },
+ );
+ const run = client.run({ input: "hi", signal: controller.signal });
+
+ const error = await run.result().catch((err: unknown) => err);
+
+ expect(error).toBe(controller.signal.reason);
+ expect(error).toMatchObject({ name: "AbortError" });
+ await expect(collect(run)).rejects.toBe(controller.signal.reason);
+ expect(served.closed).toBe(true);
+ },
+ );
+
+ it("stops the iteration at once when the loop aborts the signal", async () => {
+ fake.stream("POST", RUNS, [...PLAIN.map(frame), DONE]);
+ const controller = new AbortController();
+ const run = client.run({ input: "hi", signal: controller.signal });
+
+ const seen: string[] = [];
+ const iteration = (async () => {
+ for await (const event of run) {
+ seen.push(event.type);
+ if (event.type === "text.delta") controller.abort();
+ }
+ })();
+
+ const error = await iteration.catch((err: unknown) => err);
+
+ expect(error).toBe(controller.signal.reason);
+ expect(seen).toEqual(["run.started", "request.started", "text.delta"]);
+ });
+
+ it("drops the events not yet read when the signal aborts while the reader lags behind", async () => {
+ fake.stream("POST", RUNS, [...PLAIN.slice(0, 4).map(frame), never()]);
+ const controller = new AbortController();
+ const run = client.run({ input: "hi", signal: controller.signal });
+ await run.session;
+
+ controller.abort();
+ await expect(run.result()).rejects.toBe(controller.signal.reason);
+
+ const seen: AmspEvent[] = [];
+ const iteration = (async () => {
+ for await (const event of run) seen.push(event);
+ })();
+ await expect(iteration).rejects.toBe(controller.signal.reason);
+ expect(seen).toEqual([]);
+ });
+
+ it("rejects without waiting for the stream when the signal aborts as the response arrives", async () => {
+ const served = fake.stream("POST", RUNS, [never()]);
+ const controller = new AbortController();
+ client = new AgentClient({
+ baseUrl: BASE_URL,
+ agent: "demo/coder",
+ apiKey: KEY,
+ fetch: async (input, init) => {
+ const response = await fake.fetch(input, init);
+ controller.abort();
+ return response;
+ },
+ });
+
+ const error = await client.ask({ input: "hi", signal: controller.signal }).catch((err) => err);
+
+ expect(error).toBe(controller.signal.reason);
+ expect(served.closed).toBe(true);
+ });
+
+ it("sends nothing for a signal aborted before the run", async () => {
+ const controller = new AbortController();
+ controller.abort();
+
+ await expect(client.ask({ input: "hi", signal: controller.signal })).rejects.toBe(
+ controller.signal.reason,
+ );
+ expect(fake.calls).toEqual([]);
+ });
+
+ it("asks the server to abort with run.abort(), and the stream ends with run.done aborted", async () => {
+ const abortPath = `/sessions/${SESSION}/abort`;
+ const userAbort = { code: "user_abort", message: "Aborted by the API caller." };
+ fake.empty("POST", abortPath, 202);
+ fake.stream("POST", RUNS, [
+ ...PLAIN.slice(0, 4).map(frame),
+ fake.requested("POST", abortPath),
+ frame(ev("text.done", { role: "assistant", text: "Hello", stop_reason: "aborted" })),
+ frame(ev("request.done", { request: 1, status: "aborted", usage: null, attempt: 1 })),
+ frame(runDone({ status: "aborted", error: userAbort, session_usage: null })),
+ DONE,
+ ]);
+ const run = client.run({ input: "hi" });
+
+ await run.session;
+ await run.abort();
+
+ await expect(run.result()).resolves.toMatchObject({
+ status: "aborted",
+ error: userAbort,
+ text: "Hello",
+ });
+ });
+
+ it.each([
+ {
+ run: "a run that is over",
+ script: (f: FetchFake) => f.stream("POST", RUNS, [...PLAIN.map(frame), DONE]),
+ },
+ {
+ run: "a refused run",
+ script: (f: FetchFake) =>
+ f.json("POST", RUNS, 429, { error: { code: "too_many_runs", message: "Busy." } }),
+ },
+ ])("sends nothing when run.abort() is called on $run", async ({ script }) => {
+ script(fake);
+ const run = client.run({ input: "hi" });
+ await run.result().catch(() => {});
+
+ await run.abort();
+
+ expect(fake.calls.map((call) => call.path)).toEqual([RUNS]);
+ });
+});
+
+describe("the rest of the client", () => {
+ it("reads the Agent and one of its Sessions, and reports an unknown Session as an AmspHttpError", async () => {
+ const agent = { id: "demo/coder", name: "Coder", description: "Writes and reviews code." };
+ const session = {
+ id: SESSION,
+ agent: "demo/coder",
+ status: "idle",
+ provider: "deepseek",
+ model_id: "deepseek-chat",
+ created_at: AT,
+ last_active_at: AT,
+ };
+ fake.json("GET", "/agents/demo/coder", 200, { agent });
+ fake.json("GET", `/sessions/${SESSION}`, 200, { session });
+ fake.json("GET", "/sessions/session-unknown", 404, {
+ error: { code: "session_not_found", message: "No such API Session." },
+ });
+
+ await expect(client.agent()).resolves.toEqual(agent);
+ await expect(client.session(SESSION)).resolves.toEqual(session);
+ await expect(client.session("session-unknown")).rejects.toMatchObject({
+ status: 404,
+ code: "session_not_found",
+ });
+ });
+
+ it("says whether abort(sessionId) interrupted a run", async () => {
+ fake.empty("POST", `/sessions/${SESSION}/abort`, 202);
+ fake.empty("POST", "/sessions/session-idle/abort", 204);
+
+ await expect(client.abort(SESSION)).resolves.toBe(true);
+ await expect(client.abort("session-idle")).resolves.toBe(false);
+ });
+
+ it("posts a decision with approve(), and reports one already taken as approval_not_found", async () => {
+ fake.empty("POST", APPROVAL, 204);
+ fake.json("POST", `/sessions/${SESSION}/approvals/call_2`, 404, {
+ error: { code: "approval_not_found", message: "This approval was already decided." },
+ });
+
+ await client.approve(SESSION, "call_1", "allow");
+ await expect(client.approve(SESSION, "call_2", "deny")).rejects.toMatchObject({
+ status: 404,
+ code: "approval_not_found",
+ });
+ expect(fake.calls.map((call) => [call.path, call.body])).toEqual([
+ [APPROVAL, { decision: "allow" }],
+ [`/sessions/${SESSION}/approvals/call_2`, { decision: "deny" }],
+ ]);
+ });
+
+ it.each([
+ { args: '{"command":"ls","timeout_ms":5000}', parsed: { command: "ls", timeout_ms: 5000 } },
+ { args: "", parsed: {} },
+ { args: '{"command":"l', parsed: null },
+ { args: '["ls"]', parsed: null },
+ { args: '"ls"', parsed: null },
+ { args: "null", parsed: null },
+ ])("parseArguments reads $args as $parsed", ({ args, parsed }) => {
+ expect(
+ parseArguments({ tool_call_id: "call_1", name: "exec_command", arguments: args }),
+ ).toEqual(parsed);
+ });
+
+ it("parseArguments reads the same object from a tool_call.done and from its fragments joined, although their text differs", () => {
+ // The fragments are the provider's text; the .done is the engine's serialization of the
+ // parsed call. Neither is rebuilt from the other, so a reader parses whichever it holds.
+ const streamed = ['{"command"', ': "echo hi"}'].join("");
+ const done = '{"command":"echo hi"}';
+ const call = (args: string) => ({
+ tool_call_id: "call_1",
+ name: "exec_command",
+ arguments: args,
+ });
+
+ expect(streamed).not.toBe(done);
+ expect(parseArguments(call(done))).toEqual({ command: "echo hi" });
+ expect(parseArguments(call(streamed))).toEqual(parseArguments(call(done)));
+ });
+
+ it.each(["coder", "demo/", "/coder", "demo/coder/extra"])(
+ "refuses the agent reference %j at construction",
+ (agent) => {
+ expect(() => new AgentClient({ baseUrl: BASE_URL, agent })).toThrow(TypeError);
+ },
+ );
+
+ it("sends every request through a fetch handed to it instead of the global one", async () => {
+ const own = createFetchFake();
+ own.stream("POST", RUNS, [...PLAIN.map(frame), DONE]);
+ client = new AgentClient({ baseUrl: BASE_URL, agent: "demo/coder", fetch: own.fetch });
+
+ await expect(client.ask({ input: "hi" })).resolves.toMatchObject({ text: "Hello!" });
+ expect(own.calls).toHaveLength(1);
+ expect(fake.calls).toEqual([]);
+ });
+});
diff --git a/packages/amsp/test/helpers/fetch-fake.ts b/packages/amsp/test/helpers/fetch-fake.ts
new file mode 100644
index 00000000..ab0d70ae
--- /dev/null
+++ b/packages/amsp/test/helpers/fetch-fake.ts
@@ -0,0 +1,186 @@
+/**
+ * The package's one fetch fake: an AMSP server reduced to a script. Every request is recorded;
+ * each is answered by the route the test registered for its method and path (a JSON answer, an
+ * empty status, or an event stream), and anything unrouted gets the server's JSON 404. An event
+ * stream is written step by step: each string is sent as one chunk — so a test decides where
+ * chunks split — and a promise in the script holds the stream until it settles. An aborted
+ * request signal rejects the call before the response, as every `fetch` does; after it, the body
+ * either errors with the signal's reason (undici's and the browsers' behaviour) or, by default,
+ * is left to its reader, as a minimal `fetch` leaves it. Nothing here reaches the network.
+ */
+
+/** One request, as the fake received it. */
+export interface FetchCall {
+ method: string;
+ /** The path after the base URL, still percent-encoded. */
+ path: string;
+ headers: Headers;
+ /** The JSON body, parsed; undefined when there is none. */
+ body: unknown;
+ signal: AbortSignal | undefined;
+}
+
+/**
+ * One step of a scripted stream: a chunk to send; a promise to wait for first, or a function
+ * called when the stream reaches it, whose promise is waited for; or a broken connection (the
+ * body errors with `fail`, as a dropped socket surfaces in `fetch`).
+ */
+export type Step = string | Promise<unknown> | (() => Promise<unknown>) | { fail: unknown };
+
+/** What the server side of one streamed answer saw. */
+export interface ServedStream {
+ /** Whether the client closed the connection — cancelled the body or aborted the request — before the script ended. */
+ closed: boolean;
+}
+
+type Answer = (call: FetchCall) => Response | Promise<Response>;
+
+export const BASE_URL = "http://penguin.test/api/amsp/v1";
+
+const encoder = new TextEncoder();
+
+/** One AMSP event as the server frames it. */
+export function frame(event: object): string {
+ return `data: ${JSON.stringify(event)}\n\n`;
+}
+
+export const DONE = "data: [DONE]\n\n";
+
+/** A promise the test settles by hand, to hold a stream at a point of its script. */
+export function gate(): { promise: Promise<void>; open: () => void } {
+ let open!: () => void;
+ const promise = new Promise<void>((resolve) => {
+ open = resolve;
+ });
+ return { promise, open };
+}
+
+/** A promise that never settles: the server holds the stream open and silent. */
+export function never(): Promise<never> {
+ return new Promise<never>(() => {});
+}
+
+function scriptedBody(steps: Step[]): {
+ body: ReadableStream<Uint8Array>;
+ served: ServedStream;
+ abort: (reason: unknown) => void;
+} {
+ const served: ServedStream = { closed: false };
+ let index = 0;
+ let source!: ReadableStreamDefaultController<Uint8Array>;
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ source = controller;
+ },
+ async pull(controller) {
+ for (;;) {
+ if (served.closed) return;
+ const step = steps[index++];
+ if (step === undefined) return controller.close();
+ if (typeof step === "string") return controller.enqueue(encoder.encode(step));
+ if (typeof step === "function") await step();
+ else if (step instanceof Promise) await step;
+ else return controller.error(step.fail);
+ }
+ },
+ cancel() {
+ served.closed = true;
+ },
+ });
+ const abort = (reason: unknown) => {
+ served.closed = true;
+ source.error(reason);
+ };
+ return { body, served, abort };
+}
+
+export function createFetchFake() {
+ const calls: FetchCall[] = [];
+ const routes = new Map<string, Answer>();
+ const waiting = new Map<string, Array<(call: FetchCall) => void>>();
+ const key = (method: string, path: string) => `${method} ${path}`;
+
+ const fetch = async (
+ input: string | URL | Request,
+ init: RequestInit = {},
+ ): Promise<Response> => {
+ if (init.signal?.aborted) throw init.signal.reason;
+ const url = String(input);
+ if (!url.startsWith(BASE_URL)) throw new TypeError(`fetch failed: ${url} is off the script`);
+ const call: FetchCall = {
+ method: init.method ?? "GET",
+ path: url.slice(BASE_URL.length),
+ headers: new Headers(init.headers),
+ body: typeof init.body === "string" ? JSON.parse(init.body) : undefined,
+ signal: init.signal ?? undefined,
+ };
+ calls.push(call);
+ for (const notify of waiting.get(key(call.method, call.path)) ?? []) notify(call);
+ waiting.delete(key(call.method, call.path));
+ const answer = routes.get(key(call.method, call.path));
+ if (answer) return answer(call);
+ const notFound = { error: { code: "not_found", message: `No route for ${call.path}.` } };
+ return respond(404, JSON.stringify(notFound), "application/json");
+ };
+
+ return {
+ fetch: fetch as typeof globalThis.fetch,
+ /** Every request, in arrival order. */
+ calls,
+ /** Answers `method path` with a JSON body, once `hold` (if given) settles. */
+ json(method: string, path: string, status: number, body: unknown, hold?: Promise<unknown>) {
+ routes.set(key(method, path), async () => {
+ await hold;
+ return respond(status, JSON.stringify(body), "application/json");
+ });
+ },
+ /** Answers `method path` with a body of any type, such as a proxy's HTML error page. */
+ text(method: string, path: string, status: number, body: string, contentType: string) {
+ routes.set(key(method, path), () => respond(status, body, contentType));
+ },
+ /** Answers `method path` with a status and no body. */
+ empty(method: string, path: string, status: number) {
+ routes.set(key(method, path), () => new Response(null, { status }));
+ },
+ /**
+ * Answers `method path` with an event stream written from `steps`; with `abortErrorsBody`,
+ * aborting the request errors the body as undici and the browsers do.
+ */
+ stream(
+ method: string,
+ path: string,
+ steps: Step[],
+ { abortErrorsBody = false }: { abortErrorsBody?: boolean } = {},
+ ): ServedStream {
+ const { body, served, abort } = scriptedBody(steps);
+ routes.set(key(method, path), (call) => {
+ const signal = call.signal;
+ if (abortErrorsBody && signal) {
+ signal.addEventListener("abort", () => abort(signal.reason), { once: true });
+ }
+ return respond(200, body, "text/event-stream");
+ });
+ return served;
+ },
+ /** Resolves when `method path` has been requested (at once if it already was). */
+ requested(method: string, path: string): Promise<FetchCall> {
+ const seen = calls.find((call) => call.method === method && call.path === path);
+ if (seen) return Promise.resolve(seen);
+ return new Promise((resolve) => {
+ const list = waiting.get(key(method, path)) ?? [];
+ list.push(resolve);
+ waiting.set(key(method, path), list);
+ });
+ },
+ };
+}
+
+export type FetchFake = ReturnType<typeof createFetchFake>;
+
+function respond(
+ status: number,
+ body: string | ReadableStream<Uint8Array>,
+ contentType: string,
+): Response {
+ return new Response(body, { status, headers: { "content-type": contentType } });
+}
diff --git a/packages/amsp/test/helpers/streams.ts b/packages/amsp/test/helpers/streams.ts
new file mode 100644
index 00000000..10d9602b
--- /dev/null
+++ b/packages/amsp/test/helpers/streams.ts
@@ -0,0 +1,179 @@
+/**
+ * Two runs as the server's wire suite captured them (packages/server/test/fixtures/amsp-stream.ts,
+ * `events`), copied here event for event rather than imported: this package depends on nothing,
+ * its tests included. They are the orders the engine really produces, and the ones the first
+ * draft of the protocol got wrong:
+ * - a tool call the caller approves: the approval and the first fragment of the result arrive
+ * while the Request is still open, the rest of the result after its request.done, and a second
+ * Request answers;
+ * - a run with steering, a subagent and a compaction: a user text mid-run, a child Session's
+ * context and reply (origin-tagged), and a compaction whose summary streams as fragments with
+ * no summary.done.
+ * A plain answer (one Request, streamed text) has the same order in the fixture as the suite's
+ * own PLAIN.
+ */
+import type { AmspEvent } from "../../src/index.js";
+
+/** The `at` of every server-stamped event (run.started, run.done, approval.requested). */
+export const FIXTURE_NOW = "2026-10-07T10:00:00.000Z";
+
+const AGENT = "default_project/default_agent";
+const at = (ms: number): string => `2026-10-07T10:00:00.${String(ms).padStart(3, "0")}Z`;
+const usage = (output: number, total: number) => ({ cache_read: 0, cache_write: 0, output, total });
+
+/** The Session a captured run named in its run.started. */
+export function sessionOf(events: readonly AmspEvent[]): string {
+ const first = events[0];
+ if (first?.type !== "run.started") throw new Error("a captured run starts with run.started");
+ return first.session_id;
+}
+
+const LS_ARGS = '{"command":"ls"}';
+
+export const APPROVAL_ROUND_TRIP: readonly AmspEvent[] = [
+ {
+ type: "run.started",
+ at: FIXTURE_NOW,
+ session_id: "session-2026-10-07-10-00-00-a0000002",
+ agent: AGENT,
+ },
+ { type: "request.started", at: at(100), request: 1 },
+ {
+ type: "tool_call.delta",
+ at: at(110),
+ tool_call_id: "call_1",
+ name: "exec_command",
+ arguments: "",
+ },
+ { type: "tool_call.delta", at: at(120), tool_call_id: "call_1", name: "", arguments: LS_ARGS },
+ {
+ type: "tool_call.done",
+ at: at(140),
+ tool_call_id: "call_1",
+ name: "exec_command",
+ arguments: LS_ARGS,
+ stop_reason: "completed",
+ },
+ {
+ type: "approval.requested",
+ at: FIXTURE_NOW,
+ tool_call: { tool_call_id: "call_1", name: "exec_command", arguments: LS_ARGS },
+ },
+ { type: "approval.decided", at: at(150), tool_call_id: "call_1", decision: "allow" },
+ { type: "tool_result.delta", at: at(160), tool_call_id: "call_1", output: "" },
+ { type: "request.done", at: at(180), request: 1, status: "completed", usage: usage(12, 500) },
+ { type: "tool_result.delta", at: at(190), tool_call_id: "call_1", output: "README.md\nsrc\n" },
+ {
+ type: "tool_result.done",
+ at: at(210),
+ tool_call_id: "call_1",
+ output: "README.md\nsrc\n",
+ stop_reason: "completed",
+ },
+ { type: "request.started", at: at(220), request: 2 },
+ {
+ type: "text.done",
+ at: at(230),
+ role: "assistant",
+ text: "Two entries: README.md and src.",
+ stop_reason: "completed",
+ },
+ { type: "request.done", at: at(250), request: 2, status: "completed", usage: usage(10, 600) },
+ {
+ type: "run.done",
+ at: FIXTURE_NOW,
+ status: "completed",
+ requests: 2,
+ usage: usage(22, 1100),
+ session_usage: usage(22, 1100),
+ },
+];
+
+const CHILD = "session-2026-10-07-10-00-01-c0000001";
+
+export const MIXED_RUN: readonly AmspEvent[] = [
+ {
+ type: "run.started",
+ at: FIXTURE_NOW,
+ session_id: "session-2026-10-07-10-00-00-a0000003",
+ agent: AGENT,
+ },
+ { type: "request.started", at: at(100), request: 1 },
+ {
+ type: "text.done",
+ at: at(110),
+ role: "assistant",
+ text: "Working on it.",
+ stop_reason: "completed",
+ },
+ { type: "request.done", at: at(130), request: 1, status: "completed", usage: usage(4, 300) },
+ {
+ type: "text.done",
+ at: at(140),
+ role: "user",
+ text: "[user_steering]\nalso run the tests\n[/user_steering]",
+ stop_reason: "completed",
+ },
+ {
+ type: "context.opened",
+ at: at(150),
+ origin: [CHILD],
+ session_id: CHILD,
+ provider: "custom",
+ model_id: "m1",
+ context_window: 128000,
+ },
+ { type: "request.started", at: at(160), origin: [CHILD], request: 1 },
+ {
+ type: "text.done",
+ at: at(170),
+ origin: [CHILD],
+ role: "assistant",
+ text: "Tests pass.",
+ stop_reason: "completed",
+ },
+ {
+ type: "request.done",
+ at: at(190),
+ origin: [CHILD],
+ request: 1,
+ status: "completed",
+ usage: usage(3, 200),
+ },
+ {
+ type: "compaction.started",
+ at: at(200),
+ reason: "context",
+ mode: "summarize",
+ context: 300,
+ turns: 1,
+ },
+ { type: "summary.delta", at: at(210), text: "" },
+ { type: "summary.delta", at: at(220), text: "Summary." },
+ {
+ type: "compaction.done",
+ at: at(250),
+ reason: "context",
+ mode: "summarize",
+ status: "completed",
+ usage: usage(5, 400),
+ attempt: 1,
+ },
+ { type: "request.started", at: at(260), request: 2 },
+ {
+ type: "text.done",
+ at: at(270),
+ role: "assistant",
+ text: "Done: the build is green.",
+ stop_reason: "completed",
+ },
+ { type: "request.done", at: at(290), request: 2, status: "completed", usage: usage(6, 200) },
+ {
+ type: "run.done",
+ at: FIXTURE_NOW,
+ status: "completed",
+ requests: 3,
+ usage: usage(18, 1100),
+ session_usage: usage(15, 900),
+ },
+];
diff --git a/packages/amsp/test/sse.test.ts b/packages/amsp/test/sse.test.ts
new file mode 100644
index 00000000..6668c8ac
--- /dev/null
+++ b/packages/amsp/test/sse.test.ts
@@ -0,0 +1,120 @@
+/**
+ * readSse: the SSE framing of an AMSP body, as the SDK and the server's wire tests read it.
+ *
+ * - Given a body with keep-alive comments, fields other than `data`, a field without a colon and
+ * a multi-line data block, each event's data comes out once, its lines joined with `\n`.
+ * - Given the same body with CRLF or lone-CR line endings, delivered whole or a byte at a time
+ * (splitting line endings and UTF-8 characters), the events read the same.
+ * - Given a body that ends inside an event, that event is not dispatched.
+ * - Given a body that errors (a dropped connection), the read rejects with that error after the
+ * events that arrived.
+ * - Given a caller that stops after the first event, the body is cancelled: the connection
+ * closes rather than being read on.
+ */
+import { describe, expect, it } from "vitest";
+import { readSse } from "../src/index.js";
+
+const encoder = new TextEncoder();
+
+/** A body that delivers `text` in chunks of `size` bytes (the whole text when `size` is 0). */
+function body(text: string, size = 0): ReadableStream<Uint8Array> {
+ const bytes = encoder.encode(text);
+ const step = size || bytes.length;
+ let offset = 0;
+ return new ReadableStream<Uint8Array>({
+ pull(controller) {
+ if (offset >= bytes.length) {
+ controller.close();
+ return;
+ }
+ controller.enqueue(bytes.slice(offset, offset + step));
+ offset += step;
+ },
+ });
+}
+
+async function read(stream: ReadableStream<Uint8Array>): Promise<string[]> {
+ const out: string[] = [];
+ for await (const data of readSse(stream)) out.push(data);
+ return out;
+}
+
+const STREAM = [
+ ": keep-alive",
+ "",
+ 'data: {"type":"text.done","text":"Grüße 🐧"}',
+ "",
+ "event: ignored",
+ "id: 7",
+ "retry: 1000",
+ "data:first line",
+ "data: second line",
+ "data",
+ "",
+ ": keep-alive",
+ "",
+ "data: [DONE]",
+ "",
+ "",
+].join("\n");
+
+const EVENTS = ['{"type":"text.done","text":"Grüße 🐧"}', "first line\nsecond line\n", "[DONE]"];
+
+describe("readSse", () => {
+ it("yields each event's data once, skipping comments and every other field", async () => {
+ expect(await read(body(STREAM))).toEqual(EVENTS);
+ });
+
+ it.each([
+ { endings: "LF", ending: "\n", size: 1, how: "a byte at a time" },
+ { endings: "CRLF", ending: "\r\n", size: 0, how: "whole" },
+ { endings: "CRLF", ending: "\r\n", size: 1, how: "a byte at a time" },
+ { endings: "CRLF", ending: "\r\n", size: 3, how: "three bytes at a time" },
+ { endings: "lone-CR", ending: "\r", size: 0, how: "whole" },
+ { endings: "lone-CR", ending: "\r", size: 1, how: "a byte at a time" },
+ ])("reads $endings line endings delivered $how the same", async ({ ending, size }) => {
+ expect(await read(body(STREAM.replaceAll("\n", ending), size))).toEqual(EVENTS);
+ });
+
+ it("drops an event the body ends inside", async () => {
+ expect(await read(body('data: {"a":1}\n\ndata: {"b":2}\n'))).toEqual(['{"a":1}']);
+ expect(await read(body('data: {"a":1}\n\ndata: {"b":'))).toEqual(['{"a":1}']);
+ });
+
+ it("rejects with the body's error after the events that arrived", async () => {
+ const dropped = new TypeError("terminated");
+ let sent = false;
+ const breaking = new ReadableStream<Uint8Array>({
+ pull(controller) {
+ if (sent) return controller.error(dropped);
+ sent = true;
+ controller.enqueue(encoder.encode("data: first\n\n"));
+ },
+ });
+ const seen: string[] = [];
+
+ await expect(
+ (async () => {
+ for await (const data of readSse(breaking)) seen.push(data);
+ })(),
+ ).rejects.toBe(dropped);
+ expect(seen).toEqual(["first"]);
+ });
+
+ it("cancels the body when the caller stops after the first event", async () => {
+ let cancelled = false;
+ const endless = new ReadableStream<Uint8Array>({
+ pull(controller) {
+ controller.enqueue(encoder.encode("data: tick\n\n"));
+ },
+ cancel() {
+ cancelled = true;
+ },
+ });
+ for await (const data of readSse(endless)) {
+ expect(data).toBe("tick");
+ break;
+ }
+ expect(cancelled).toBe(true);
+ });
+});
diff --git a/packages/amsp/tsconfig.json b/packages/amsp/tsconfig.json
new file mode 100644
index 00000000..77a77870
--- /dev/null
+++ b/packages/amsp/tsconfig.json
@@ -0,0 +1,9 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "rootDir": ".",
+ "lib": ["ES2023", "DOM", "DOM.Iterable"],
+ "types": []
+ },
+ "include": ["src", "test"]
+}
diff --git a/packages/amsp/tsup.config.ts b/packages/amsp/tsup.config.ts
new file mode 100644
index 00000000..b6aabfe1
--- /dev/null
+++ b/packages/amsp/tsup.config.ts
@@ -0,0 +1,15 @@
+import { defineConfig } from "tsup";
+
+export default defineConfig({
+ entry: { index: "src/index.ts" },
+ format: ["esm"],
+ // The package runs in Node 24 and in browsers: nothing Node-specific is resolved or injected,
+ // and it has no runtime dependency to bundle.
+ platform: "neutral",
+ // One target for every package here (packages/cli/test/tsup-target.test.ts), matching
+ // engines.node. Current browsers parse the syntax Node 24 does.
+ target: "node24",
+ dts: true,
+ clean: true,
+ sourcemap: true,
+});
diff --git a/packages/cli/src/client.ts b/packages/cli/src/client.ts
index e0b8e3b9..6d2a9ac4 100644
--- a/packages/cli/src/client.ts
+++ b/packages/cli/src/client.ts
@@ -19,12 +19,21 @@
* Token resolution: ADELIE_API_TOKEN, else `<root>/api-token` (written by the server
* each boot). A 401 with a file-sourced token re-reads the file once and retries — the
* server may have restarted (and rotated the token) since the first read.
+ *
+ * A 403 `human_required` — a write the server takes only from a person's sign-in, such as
+ * those that change an Agent's exposure — retries the same request once as the person's
+ * stored sign-in (`<root>/cli-session.json`, written by `penguin auth login` or
+ * `penguin auth token`), sent as the `penguin_session` cookie in place of the token. Only for
+ * a loopback target, only for a sign-in made to a loopback server, and only outside a Session
+ * (ADELIE_SESSION_ID unset): inside one the command is an Agent's, and the refusal is the
+ * point. Every other request goes exactly as above.
*/
import { spawn } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { resolveRoot } from "@lmliheng/penguin-core";
import { liveServerLock } from "@lmliheng/penguin-server/lock";
+import { readSession } from "./auth-session.js";
import type { Messages } from "./i18n.js";
/** Session-id shape (core's convention); a full id needs no directory search. */
@@ -36,6 +45,12 @@ const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
/** How the auth token was obtained; decides whether a 401 retries after re-reading the file. */
export type TokenSource = "env" | "file" | "none";
+/** The server's session cookie (auth/middleware.ts SESSION_COOKIE): a stored sign-in goes as it. */
+const SESSION_COOKIE = "penguin_session";
+
+/** The server's refusal of the local API token on a write only a person may make (requireHuman). */
+const HUMAN_REQUIRED = "human_required";
+
export interface Connection {
/** Normalized base URL, no trailing slash. */
baseUrl: string;
@@ -86,6 +101,32 @@ function readTokenFile(root: string): string | null {
}
}
+/**
+ * The person's stored sign-in on this data root, for the one retry after a `human_required`
+ * refusal (see the module doc); null inside a Session, where the command is an Agent's, and for a
+ * sign-in to a server elsewhere, whose session must not be sent to this one.
+ */
+function readStoredSignIn(root: string): string | null {
+ if (process.env.ADELIE_SESSION_ID?.trim()) return null;
+ const session = readSession(root);
+ if (session === null) return null;
+ try {
+ return isLoopbackUrl(new URL(session.server)) ? session.token : null;
+ } catch {
+ return null;
+ }
+}
+
+/** The error code of a JSON error body (`{error: {code}}`), or null for any other body. */
+async function errorCodeOf(res: Response): Promise<string | null> {
+ try {
+ const body = (await res.json()) as { error?: { code?: unknown } } | null;
+ return typeof body?.error?.code === "string" ? body.error.code : null;
+ } catch {
+ return null;
+ }
+}
+
/**
* The CLI entry script for auto-start, or null when this process cannot re-run itself
* with plain node (a tsx dev run has a .ts entry) — same rule as serve.ts's cliEntryFor.
@@ -234,8 +275,9 @@ export class ServerClient {
/**
* One JSON request. 401 with a file-sourced token re-reads the file once (the server
- * may have restarted and rotated it) and retries; every other non-2xx becomes an
- * ApiError carrying the server's code and message.
+ * may have restarted and rotated it) and retries; 403 `human_required` retries once as the
+ * person's stored sign-in (see fetchAuthed); every other non-2xx becomes an ApiError
+ * carrying the server's code and message.
*/
async request<T>(method: string, apiPath: string, body?: unknown): Promise<T> {
const res = await this.fetchAuthed(apiPath, {
@@ -252,8 +294,17 @@ export class ServerClient {
return (text === "" ? undefined : JSON.parse(text)) as T;
}
- /** The authenticated fetch with the one-shot 401 file-token refresh. */
+ /**
+ * The authenticated fetch: the one-shot 401 file-token refresh, then the one-shot retry of a
+ * 403 `human_required` as the person's stored sign-in.
+ */
private async fetchAuthed(apiPath: string, init: RequestInit): Promise<Response> {
+ const res = await this.fetchWithToken(apiPath, init);
+ return res.status === 403 ? this.retryAsPerson(apiPath, init, res) : res;
+ }
+
+ /** The token's fetch, with the one-shot 401 file-token refresh. */
+ private async fetchWithToken(apiPath: string, init: RequestInit): Promise<Response> {
const res = await fetch(`${this.conn.baseUrl}${apiPath}`, init);
if (res.status !== 401) return res;
if (this.tokenSource === "env" || !this.conn.loopback) return res;
@@ -266,6 +317,35 @@ export class ServerClient {
return fetch(`${this.conn.baseUrl}${apiPath}`, { ...init, headers });
}
+ /**
+ * `refused` was a 403. When it is `human_required` and there is a stored sign-in to use (see the
+ * module doc), sends the same request once more as that sign-in — the session cookie, no
+ * Bearer, since the server reads a Bearer first — and answers with that. The refusal stands
+ * when there is no usable sign-in, and when the server does not accept the sign-in either (a
+ * 401: it expired or was revoked), so the caller still sees `human_required`.
+ */
+ private async retryAsPerson(
+ apiPath: string,
+ init: RequestInit,
+ refused: Response,
+ ): Promise<Response> {
+ if (!this.conn.loopback) return refused;
+ const signIn = readStoredSignIn(this.conn.root);
+ if (signIn === null) return refused;
+ if ((await errorCodeOf(refused.clone())) !== HUMAN_REQUIRED) return refused;
+ const headers: Record<string, string> = { cookie: `${SESSION_COOKIE}=${signIn}` };
+ for (const [name, value] of Object.entries((init.headers ?? {}) as Record<string, string>)) {
+ if (name.toLowerCase() !== "authorization") headers[name] = value;
+ }
+ const retried = await fetch(`${this.conn.baseUrl}${apiPath}`, { ...init, headers });
+ if (retried.status === 401) {
+ void retried.body?.cancel();
+ return refused;
+ }
+ void refused.body?.cancel();
+ return retried;
+ }
+
private async toError(res: Response): Promise<ApiError> {
let code = "http_error";
let message = "";
diff --git a/packages/cli/src/commands/agent.ts b/packages/cli/src/commands/agent.ts
index f5e06dd0..5560f898 100644
--- a/packages/cli/src/commands/agent.ts
+++ b/packages/cli/src/commands/agent.ts
@@ -1,22 +1,303 @@
/**
- * `penguin agent` — list and create agents through the server.
+ * `penguin agent` — list and create agents through the server, and manage an agent's public API.
*
* penguin agent ls [--project-id <id>] [--json] [--server <url>]
* penguin agent create --agent-id <id> [--name <s>] [--description <s>]
* [--plugins <a,b>] [--project-id <id>] [--json] [--server <url>]
+ * penguin agent api status --agent-id <id> [--project-id <id>] [--json] [--server <url>]
+ * penguin agent api enable --agent-id <id> [--open | --no-open] [--approve <mode>] …
+ * penguin agent api disable --agent-id <id> …
+ * penguin agent api set --agent-id <id> [--open | --no-open] [--approve <mode>] …
+ * penguin agent api keys ls --agent-id <id> …
+ * penguin agent api keys create --agent-id <id> --name <s> …
+ * penguin agent api keys rm <keyId> --agent-id <id> …
+ * penguin agent api server on|off [--json] [--server <url>]
*
* `create` mirrors the Web dialog's fields: id (required), display name, description,
* and library plugins to seed (comma-separated names; unknown names are rejected by the
* server before anything is created).
+ *
+ * `api` is the Agent page's API tab over /api/projects/:p/agents/:a/api: whether external
+ * programs may talk to the agent, keyless access, the approval mode API conversations are
+ * created with (`--approve`, validated as `run` and `chat` validate theirs), and the keys. The
+ * agent is always named with `--agent-id` — exposing one is never left to a default. `enable`,
+ * `disable` and `set` print the resulting status, as `status` does; its last line is the
+ * server-wide switch, which the settings read reports to any member and which `server on|off`
+ * (admins only) writes. `keys
+ * create` prints the key bare on stdout — the only time it exists anywhere — and everything else
+ * on stderr, so `KEY=$(penguin agent api keys create …)` captures exactly the key.
+ *
+ * The writes (`enable`, `disable`, `set`, `keys create`, `keys rm`, `server`) take a person's
+ * sign-in: the server refuses the local API token on them with 403 `human_required`, so that
+ * an Agent cannot expose itself from its own shell. Outside a Session the client then retries
+ * once as the stored `penguin auth login` (client.ts); when that is missing or refused too, the
+ * write prints what to run instead.
* Docs: /docs/cli § "penguin agent".
*/
import type { Command } from "commander";
-import type { AgentCreateResponse, AgentSummary } from "@lmliheng/penguin-server/api";
-import { resolveConnection, resolveProjectId, ServerClient } from "../client.js";
+import type {
+ AgentApiKeyCreateResponse,
+ AgentApiResponse,
+ AgentApiSettings,
+ AgentApiUpdateRequest,
+ AgentCreateResponse,
+ AgentSummary,
+ ServerSettingsResponse,
+} from "@lmliheng/penguin-server/api";
+import { resolveApprovalMode } from "../approval.js";
+import { ApiError, resolveConnection, resolveProjectId, ServerClient } from "../client.js";
import { listAgents } from "../server-session.js";
-import { renderTable } from "../table.js";
+import { displayWidth, renderTable } from "../table.js";
import type { Messages } from "../i18n.js";
+const enc = encodeURIComponent;
+
+interface ApiOpts {
+ agentId: string;
+ projectId?: string;
+ json?: boolean;
+ server?: string;
+ open?: boolean;
+ approve?: string;
+ name?: string;
+}
+
+async function connect(opts: { server?: string }, t: Messages): Promise<ServerClient> {
+ return new ServerClient(await resolveConnection({ server: opts.server }, t), t);
+}
+
+/** The agent's API, as the server names it: project and agent ids, and the routes under it. */
+function target(opts: ApiOpts): { projectId: string; agentId: string; ref: string; path: string } {
+ const projectId = resolveProjectId(opts.projectId);
+ const agentId = String(opts.agentId).trim();
+ return {
+ projectId,
+ agentId,
+ ref: `${projectId}/${agentId}`,
+ path: `/api/projects/${enc(projectId)}/agents/${enc(agentId)}/api`,
+ };
+}
+
+/** What `--open` / `--no-open` / `--approve` ask to change; an invalid mode exits before any request. */
+function settingsPatch(opts: ApiOpts, t: Messages): AgentApiUpdateRequest {
+ return {
+ ...(typeof opts.open === "boolean" ? { open: opts.open } : {}),
+ ...(opts.approve !== undefined ? { approvalMode: resolveApprovalMode(opts.approve, t) } : {}),
+ };
+}
+
+/** Prints the settings as `status` shows them: a heading and one aligned line per fact, or JSON. */
+function printStatus(
+ client: ServerClient,
+ ref: string,
+ res: AgentApiResponse,
+ json: boolean,
+ t: Messages,
+): void {
+ const baseUrl = `${client.conn.baseUrl}/api/amsp/v1`;
+ const settings: AgentApiSettings = res.api;
+ const server = res.serverEnabled;
+ if (json) {
+ process.stdout.write(
+ `${JSON.stringify({ agent: ref, baseUrl, api: settings, serverEnabled: server })}\n`,
+ );
+ return;
+ }
+ const yesNo = (on: boolean) => (on ? t.agent.apiYes() : t.agent.apiNo());
+ const rows: Array<[string, string]> = [
+ [t.agent.apiFieldEnabled(), yesNo(settings.enabled)],
+ [t.agent.apiFieldOpen(), yesNo(settings.open)],
+ [t.agent.apiFieldApproval(), settings.approvalMode],
+ [t.agent.apiFieldBaseUrl(), baseUrl],
+ [t.agent.apiFieldAgentId(), ref],
+ [t.agent.apiFieldKeys(), String(settings.keys.length)],
+ [t.agent.apiFieldServer(), server ? t.agent.apiServerOn() : t.agent.apiServerOff()],
+ ];
+ const width = Math.max(...rows.map(([label]) => displayWidth(label)));
+ const lines = rows.map(
+ ([label, value]) => ` ${label}${" ".repeat(width - displayWidth(label))} ${value}`,
+ );
+ process.stdout.write(`${t.agent.apiStatusTitle(ref)}\n${lines.join("\n")}\n`);
+}
+
+/**
+ * A write that changes who can reach an agent. The server's 403 `human_required` that is left
+ * after the client's retry as a stored sign-in — the request carried the local API token, and no
+ * sign-in the server accepts stood in for it — becomes the line saying what to run.
+ */
+async function exposureWrite<T>(
+ client: ServerClient,
+ method: string,
+ apiPath: string,
+ body: unknown,
+ t: Messages,
+): Promise<T> {
+ try {
+ return await client.request<T>(method, apiPath, body);
+ } catch (err) {
+ if (err instanceof ApiError && err.code === "human_required") {
+ throw new Error(t.agent.apiSignInRequired());
+ }
+ throw err;
+ }
+}
+
+/** One PUT of the agent's API settings, then the status it left. */
+async function writeSettings(opts: ApiOpts, patch: AgentApiUpdateRequest, t: Messages) {
+ const { path, ref } = target(opts);
+ const client = await connect(opts, t);
+ const res = await exposureWrite<AgentApiResponse>(client, "PUT", path, patch, t);
+ printStatus(client, ref, res, opts.json === true, t);
+ // The Web App asks before keyless access goes on; a terminal has no dialog, so it warns on
+ // stderr once the switch is on (stdout stays the status or the JSON).
+ if (patch.open === true && res.api.open) process.stderr.write(`${t.agent.apiOpenWarning()}\n`);
+}
+
+function registerApiCommands(agent: Command, t: Messages): void {
+ const api = agent.command("api").description(t.agent.apiDesc);
+ /** The options every command naming an agent takes. */
+ const forAgent = (cmd: Command): Command =>
+ cmd
+ .requiredOption("--agent-id <id>", t.common.agentId)
+ .option("--project-id <id>", t.common.projectId)
+ .option("--json", t.common.json)
+ .option("--server <url>", t.common.server);
+ /** `--open` / `--no-open` / `--approve`: neither switch given leaves `open` undefined. */
+ const settingsOptions = (cmd: Command): Command =>
+ cmd
+ .option("--open", t.agent.apiOpen)
+ .option("--no-open", t.agent.apiNoOpen)
+ .option("--approve <mode>", t.agent.apiApprove);
+
+ forAgent(api.command("status").description(t.agent.apiStatusDesc)).action(
+ async (opts: ApiOpts) => {
+ const { path, ref } = target(opts);
+ const client = await connect(opts, t);
+ const res = await client.request<AgentApiResponse>("GET", path);
+ printStatus(client, ref, res, opts.json === true, t);
+ },
+ );
+
+ settingsOptions(forAgent(api.command("enable").description(t.agent.apiEnableDesc))).action(
+ async (opts: ApiOpts) => {
+ await writeSettings(opts, { enabled: true, ...settingsPatch(opts, t) }, t);
+ },
+ );
+
+ forAgent(api.command("disable").description(t.agent.apiDisableDesc)).action(
+ async (opts: ApiOpts) => {
+ await writeSettings(opts, { enabled: false }, t);
+ },
+ );
+
+ settingsOptions(forAgent(api.command("set").description(t.agent.apiSetDesc))).action(
+ async (opts: ApiOpts) => {
+ const patch = settingsPatch(opts, t);
+ if (Object.keys(patch).length === 0) {
+ process.stderr.write(`${t.agent.apiNothingToSet()}\n`);
+ process.exitCode = 1;
+ return;
+ }
+ await writeSettings(opts, patch, t);
+ },
+ );
+
+ const keys = api.command("keys").description(t.agent.apiKeysDesc);
+
+ forAgent(keys.command("ls").description(t.agent.apiKeysLsDesc)).action(async (opts: ApiOpts) => {
+ const { path, ref } = target(opts);
+ const client = await connect(opts, t);
+ const res = await client.request<AgentApiResponse>("GET", path);
+ if (opts.json === true) {
+ process.stdout.write(`${JSON.stringify(res.api.keys)}\n`);
+ return;
+ }
+ if (res.api.keys.length === 0) {
+ process.stdout.write(`${t.agent.apiKeysEmpty(ref)}\n`);
+ return;
+ }
+ process.stdout.write(
+ renderTable(
+ [
+ t.agent.apiColKeyId(),
+ t.agent.apiColKeyName(),
+ t.agent.apiColPrefix(),
+ t.agent.apiColCreated(),
+ t.agent.apiColLastUsed(),
+ ],
+ res.api.keys.map((k) => [
+ k.keyId,
+ k.name,
+ `${k.prefix}…`,
+ k.createdAt,
+ k.lastUsedAt ?? t.agent.apiKeyNever(),
+ ]),
+ ),
+ );
+ });
+
+ forAgent(keys.command("create").description(t.agent.apiKeysCreateDesc))
+ .requiredOption("--name <name>", t.agent.apiKeyName)
+ .action(async (opts: ApiOpts) => {
+ const { path, ref } = target(opts);
+ const client = await connect(opts, t);
+ const res = await exposureWrite<AgentApiKeyCreateResponse>(
+ client,
+ "POST",
+ `${path}/keys`,
+ { name: String(opts.name) },
+ t,
+ );
+ if (opts.json === true) {
+ process.stdout.write(`${JSON.stringify(res)}\n`);
+ return;
+ }
+ process.stdout.write(`${res.secret}\n`);
+ process.stderr.write(`${t.agent.apiKeyCreated(res.key.name, res.key.prefix, ref)}\n`);
+ });
+
+ forAgent(keys.command("rm <keyId>").description(t.agent.apiKeysRmDesc)).action(
+ async (keyId: string, opts: ApiOpts) => {
+ const { path, ref } = target(opts);
+ const client = await connect(opts, t);
+ await exposureWrite<void>(client, "DELETE", `${path}/keys/${enc(keyId)}`, undefined, t);
+ if (opts.json === true) {
+ process.stdout.write(`${JSON.stringify({ deleted: keyId })}\n`);
+ return;
+ }
+ process.stdout.write(`${t.agent.apiKeyDeleted(keyId, ref)}\n`);
+ },
+ );
+
+ api
+ .command("server <state>")
+ .description(t.agent.apiServerDesc)
+ .option("--json", t.common.json)
+ .option("--server <url>", t.common.server)
+ .action(async (state: string, opts: { json?: boolean; server?: string }) => {
+ const wanted = state.trim().toLowerCase();
+ if (wanted !== "on" && wanted !== "off") {
+ process.stderr.write(`${t.agent.apiServerStateInvalid(state)}\n`);
+ process.exitCode = 1;
+ return;
+ }
+ const client = await connect(opts, t);
+ const res = await exposureWrite<ServerSettingsResponse>(
+ client,
+ "PUT",
+ "/api/admin/settings",
+ { agentApiEnabled: wanted === "on" },
+ t,
+ );
+ const on = res.settings.agentApiEnabled;
+ if (opts.json === true) {
+ process.stdout.write(`${JSON.stringify({ agentApiEnabled: on })}\n`);
+ return;
+ }
+ process.stdout.write(`${t.agent.apiServerSet(on)}\n`);
+ });
+}
+
export function registerAgentCommand(program: Command, t: Messages): void {
const agent = program.command("agent").description(t.agent.desc);
@@ -83,4 +364,6 @@ export function registerAgentCommand(program: Command, t: Messages): void {
}
process.stdout.write(`${t.agent.created(res.agent.agentId, projectId)}\n`);
});
+
+ registerApiCommands(agent, t);
}
diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.ts
index 3f2519ad..3798266e 100644
--- a/packages/cli/src/i18n.ts
+++ b/packages/cli/src/i18n.ts
@@ -178,6 +178,58 @@ export interface Messages {
colName(): string;
colSessions(): string;
colDescription(): string;
+ /** `penguin agent api …`: an agent's public API (this server's switches, approval mode and keys). */
+ apiDesc: string;
+ apiStatusDesc: string;
+ apiEnableDesc: string;
+ apiDisableDesc: string;
+ apiSetDesc: string;
+ /** --open / --no-open: keyless access on or off. */
+ apiOpen: string;
+ apiNoOpen: string;
+ /** --approve on enable/set: the mode API conversations are created with. */
+ apiApprove: string;
+ /** `set` given nothing to change. */
+ apiNothingToSet(): string;
+ apiKeysDesc: string;
+ apiKeysLsDesc: string;
+ apiKeysCreateDesc: string;
+ apiKeysRmDesc: string;
+ /** --name of `keys create`. */
+ apiKeyName: string;
+ apiServerDesc: string;
+ /** `server <state>` given something other than on/off. */
+ apiServerStateInvalid(value: string): string;
+ /** The status block: its heading, then one labelled line per fact. */
+ apiStatusTitle(agentRef: string): string;
+ apiFieldEnabled(): string;
+ apiFieldOpen(): string;
+ apiFieldApproval(): string;
+ apiFieldBaseUrl(): string;
+ apiFieldAgentId(): string;
+ apiFieldKeys(): string;
+ apiFieldServer(): string;
+ apiYes(): string;
+ apiNo(): string;
+ apiServerOn(): string;
+ apiServerOff(): string;
+ /** `keys ls` columns, and the line for an agent with none. */
+ apiColKeyId(): string;
+ apiColKeyName(): string;
+ apiColPrefix(): string;
+ apiColCreated(): string;
+ apiColLastUsed(): string;
+ apiKeyNever(): string;
+ apiKeysEmpty(agentRef: string): string;
+ /** stderr beside the bare secret on stdout. */
+ apiKeyCreated(name: string, prefix: string, agentRef: string): string;
+ apiKeyDeleted(keyId: string, agentRef: string): string;
+ /** After `server on|off`. */
+ apiServerSet(on: boolean): string;
+ /** A write refused 403 human_required: it carried the local API token, and no stored sign-in stood in. */
+ apiSignInRequired(): string;
+ /** On stderr after `--open` switched keyless access on. */
+ apiOpenWarning(): string;
};
/** `penguin project`: project listing. */
project: {
@@ -1240,6 +1292,53 @@ const en: Messages = {
colName: () => "NAME",
colSessions: () => "SESSIONS",
colDescription: () => "DESCRIPTION",
+ apiDesc: "Manage an agent's public API: the switch, keyless access, approval mode and keys",
+ apiStatusDesc: "Show the agent's API settings, its address and the server-wide switch",
+ apiEnableDesc: "Turn the agent's API on",
+ apiDisableDesc: "Turn the agent's API off (settings and keys are kept)",
+ apiSetDesc: "Change keyless access or the approval mode without turning the API on or off",
+ apiOpen: "Allow keyless access: anything that can reach the server can talk to the agent",
+ apiNoOpen: "Require a key",
+ apiApprove:
+ "Approval mode new API conversations start with: allow-all, deny-all, read-only or always-ask (asks go to the caller)",
+ apiNothingToSet: () => "Nothing to change: pass --open, --no-open or --approve <mode>.",
+ apiKeysDesc: "Manage the agent's API keys",
+ apiKeysLsDesc: "List the agent's API keys",
+ apiKeysCreateDesc: "Create an API key; the key is printed once, alone on stdout",
+ apiKeysRmDesc: "Delete an API key; programs using it are refused from then on",
+ apiKeyName: "Name of the key (1-64 characters)",
+ apiServerDesc: "Turn the Agent API on or off for the whole server (admins only)",
+ apiServerStateInvalid: (value) => `Invalid state "${value}": expected on or off.`,
+ apiStatusTitle: (agentRef) => `Agent API of ${agentRef}`,
+ apiFieldEnabled: () => "Enabled",
+ apiFieldOpen: () => "Keyless access",
+ apiFieldApproval: () => "Approval mode",
+ apiFieldBaseUrl: () => "Base URL",
+ apiFieldAgentId: () => "Agent ID",
+ apiFieldKeys: () => "Keys",
+ apiFieldServer: () => "Server switch",
+ apiYes: () => "yes",
+ apiNo: () => "no",
+ apiServerOn: () => "on",
+ apiServerOff: () => "off (every API request is refused)",
+ apiColKeyId: () => "ID",
+ apiColKeyName: () => "NAME",
+ apiColPrefix: () => "PREFIX",
+ apiColCreated: () => "CREATED",
+ apiColLastUsed: () => "LAST USED",
+ apiKeyNever: () => "never",
+ apiKeysEmpty: (agentRef) => `${agentRef} has no API keys.`,
+ apiKeyCreated: (name, prefix, agentRef) =>
+ `Created key "${name}" (${prefix}…) for ${agentRef}. It is shown once, above; store it now.`,
+ apiKeyDeleted: (keyId, agentRef) => `Deleted key ${keyId} of ${agentRef}.`,
+ apiServerSet: (on) =>
+ on
+ ? "The Agent API is on for this server."
+ : "The Agent API is off for this server: every request is refused; per-agent settings and keys are kept.",
+ apiSignInRequired: () =>
+ "Sign in first: `penguin auth login` (or `penguin auth token` on the server's machine). The local API token may not change an Agent's exposure.",
+ apiOpenWarning: () =>
+ "Warning: keyless access is on. Anything that can reach this server's address can now talk to the agent without a key, on the Project's models and credentials. Keep it on only for a server that listens on loopback; `--no-open` turns it off.",
},
project: {
desc: "Manage projects",
@@ -2305,6 +2404,53 @@ const zh: Messages = {
colName: () => "名称",
colSessions: () => "会话数",
colDescription: () => "描述",
+ apiDesc: "管理 Agent 的对外 API:开关、无密钥访问、审批模式与密钥",
+ apiStatusDesc: "查看 Agent 的 API 设置、访问地址与服务器总开关",
+ apiEnableDesc: "开启 Agent 的 API 访问",
+ apiDisableDesc: "关闭 Agent 的 API 访问(设置与密钥保留)",
+ apiSetDesc: "更改无密钥访问或审批模式,不改变开关",
+ apiOpen: "允许无密钥访问:任何能访问服务器的程序都能与该 Agent 对话",
+ apiNoOpen: "要求密钥",
+ apiApprove:
+ "新建 API 会话使用的审批模式:allow-all、deny-all、read-only 或 always-ask(需要确认时发给调用方)",
+ apiNothingToSet: () => "没有要更改的内容:请给出 --open、--no-open 或 --approve <mode>。",
+ apiKeysDesc: "管理 Agent 的 API 密钥",
+ apiKeysLsDesc: "列出 Agent 的 API 密钥",
+ apiKeysCreateDesc: "新建 API 密钥;密钥只输出一次,单独占据 stdout",
+ apiKeysRmDesc: "删除 API 密钥;使用它的程序此后会被拒绝",
+ apiKeyName: "密钥名称(1–64 个字符)",
+ apiServerDesc: "为整个服务器开启或关闭 Agent API(仅管理员)",
+ apiServerStateInvalid: (value) => `状态「${value}」无效:应为 on 或 off。`,
+ apiStatusTitle: (agentRef) => `${agentRef} 的 Agent API`,
+ apiFieldEnabled: () => "已开启",
+ apiFieldOpen: () => "无密钥访问",
+ apiFieldApproval: () => "审批模式",
+ apiFieldBaseUrl: () => "Base URL",
+ apiFieldAgentId: () => "Agent ID",
+ apiFieldKeys: () => "密钥数",
+ apiFieldServer: () => "服务器总开关",
+ apiYes: () => "是",
+ apiNo: () => "否",
+ apiServerOn: () => "开",
+ apiServerOff: () => "关(所有 API 请求均被拒绝)",
+ apiColKeyId: () => "ID",
+ apiColKeyName: () => "名称",
+ apiColPrefix: () => "前缀",
+ apiColCreated: () => "创建时间",
+ apiColLastUsed: () => "最近使用",
+ apiKeyNever: () => "从未",
+ apiKeysEmpty: (agentRef) => `${agentRef} 还没有 API 密钥。`,
+ apiKeyCreated: (name, prefix, agentRef) =>
+ `已为 ${agentRef} 新建密钥「${name}」(${prefix}…)。密钥只在上方显示这一次,请立即保存。`,
+ apiKeyDeleted: (keyId, agentRef) => `已删除 ${agentRef} 的密钥 ${keyId}。`,
+ apiServerSet: (on) =>
+ on
+ ? "这台服务器的 Agent API 已开启。"
+ : "这台服务器的 Agent API 已关闭:所有请求均被拒绝,各 Agent 的设置与密钥保留。",
+ apiSignInRequired: () =>
+ "请先登录:`penguin auth login`(或在服务器本机运行 `penguin auth token`)。本机 API token 不能改变 Agent 的对外暴露。",
+ apiOpenWarning: () =>
+ "警告:已开启无密钥访问。任何能访问此服务器地址的程序现在都无需密钥即可与该 Agent 对话,用的是本 Project 的模型与凭据。仅建议在只监听本机的服务器上保持开启;`--no-open` 可关闭。",
},
project: {
desc: "管理 Project",
diff --git a/packages/cli/test/agent-api.test.ts b/packages/cli/test/agent-api.test.ts
new file mode 100644
index 00000000..b2eb044d
--- /dev/null
+++ b/packages/cli/test/agent-api.test.ts
@@ -0,0 +1,316 @@
+/**
+ * `penguin agent api …`, driven through `cli()` in-process against the fake server's agent API
+ * and admin settings routes.
+ *
+ * - `keys create` prints the key bare on stdout and everything else on stderr; listing the keys
+ * afterwards names the new one by its prefix, never by the secret.
+ * - `enable --open --approve read-only` sends one PUT turning the API on with keyless access and
+ * that approval mode, and prints the status it left; `disable` sends only the switch, so keyless
+ * access and the mode stay as they were.
+ * - `set` sends only what it is given; given nothing, it sends nothing and fails.
+ * - An unknown `--approve` mode fails before any request.
+ * - The agent is never a default: without `--agent-id`, nothing is sent.
+ * - `status` shows the server-wide switch to any member, an admin or not, from the agent's own
+ * settings read: the admin settings are never asked.
+ * - `server off` / `server on` write the server-wide switch; any other state sends nothing.
+ * - `keys rm` deletes the key; an unknown key fails with the server's code.
+ * - The token file goes as Bearer on every request, a stored sign-in notwithstanding, wherever
+ * the server takes the token.
+ * - A write the server refuses for the token (403 `human_required`) is retried once as the
+ * person's stored sign-in (`penguin auth login`), alone as the session cookie, and goes through.
+ * - With no stored sign-in, each such write prints the sign-in hint, exits 1 and changes nothing.
+ * - Inside a Session, or for a sign-in to another server, the stored sign-in is never sent: the
+ * write prints the hint and exits 1.
+ * - A stored sign-in the server no longer accepts leaves the refusal: the hint, exit 1.
+ */
+import fs from "node:fs";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { writeSession } from "../src/auth-session.js";
+import { cli } from "../src/index.js";
+import { getMessages } from "../src/i18n.js";
+import { FakeServer } from "./fake-server.js";
+
+const t = getMessages("en");
+const REF = "default_project/default_agent";
+const API = "/api/projects/default_project/agents/default_agent/api";
+
+let server: FakeServer;
+let uninstall: () => void;
+let stdout: string[];
+let stderr: string[];
+let restore: Array<{ mockRestore(): void }>;
+
+beforeEach(() => {
+ server = new FakeServer();
+ uninstall = server.install();
+ stdout = [];
+ stderr = [];
+ restore = [
+ vi.spyOn(process.stdout, "write").mockImplementation((chunk) => {
+ stdout.push(String(chunk));
+ return true;
+ }),
+ vi.spyOn(process.stderr, "write").mockImplementation((chunk) => {
+ stderr.push(String(chunk));
+ return true;
+ }),
+ ];
+});
+afterEach(() => {
+ for (const spy of restore) spy.mockRestore();
+ uninstall();
+});
+
+const out = () => stdout.join("");
+const err = () => stderr.join("");
+/** The writes sent to the agent's API settings and to the admin settings, in order. */
+const writes = () =>
+ server.requests
+ .filter((r) => r.method !== "GET")
+ .map((r) => [r.method, r.path, r.body ?? null] as const);
+
+describe("penguin agent api keys", () => {
+ it("create prints the key bare on stdout and the rest on stderr", async () => {
+ expect(
+ await cli(["agent", "api", "keys", "create", "--agent-id", "default_agent", "--name", "ci"]),
+ ).toBe(0);
+ const [key] = server.agentApi.get(REF)!.keys;
+ const [secret] = server.mintedSecrets;
+ expect(out()).toBe(`${secret}\n`);
+ expect(err()).toBe(`${t.agent.apiKeyCreated("ci", String(key!.prefix), REF)}\n`);
+ expect(writes()).toEqual([["POST", `${API}/keys`, { name: "ci" }]]);
+
+ stdout.length = 0;
+ expect(await cli(["agent", "api", "keys", "ls", "--agent-id", "default_agent"])).toBe(0);
+ expect(out()).toContain(`${String(key!.prefix)}…`);
+ expect(out()).toContain(t.agent.apiKeyNever());
+ expect(out()).not.toContain(secret!);
+ });
+
+ it("rm deletes the key; an unknown key fails with the server's code", async () => {
+ await cli(["agent", "api", "keys", "create", "--agent-id", "default_agent", "--name", "ci"]);
+ stdout.length = 0;
+ expect(await cli(["agent", "api", "keys", "rm", "key1", "--agent-id", "default_agent"])).toBe(
+ 0,
+ );
+ expect(out()).toBe(`${t.agent.apiKeyDeleted("key1", REF)}\n`);
+ expect(server.agentApi.get(REF)!.keys).toEqual([]);
+
+ expect(await cli(["agent", "api", "keys", "rm", "key1", "--agent-id", "default_agent"])).toBe(
+ 1,
+ );
+ expect(err()).toContain("key_not_found");
+ });
+
+ it("ls says so when the agent has no keys", async () => {
+ expect(await cli(["agent", "api", "keys", "ls", "--agent-id", "default_agent"])).toBe(0);
+ expect(out()).toBe(`${t.agent.apiKeysEmpty(REF)}\n`);
+ });
+});
+
+describe("penguin agent api enable / disable / set", () => {
+ it("enable --open --approve read-only sends one PUT and prints the status it left", async () => {
+ expect(
+ await cli([
+ "agent",
+ "api",
+ "enable",
+ "--agent-id",
+ "default_agent",
+ "--open",
+ "--approve",
+ "read-only",
+ ]),
+ ).toBe(0);
+ expect(writes()).toEqual([
+ ["PUT", API, { enabled: true, open: true, approvalMode: "read-only" }],
+ ]);
+ const text = out();
+ expect(text).toContain(t.agent.apiStatusTitle(REF));
+ expect(text).toMatch(new RegExp(`${t.agent.apiFieldEnabled()}\\s+${t.agent.apiYes()}`));
+ expect(text).toMatch(new RegExp(`${t.agent.apiFieldOpen()}\\s+${t.agent.apiYes()}`));
+ expect(text).toMatch(new RegExp(`${t.agent.apiFieldApproval()}\\s+read-only`));
+ expect(text).toContain("http://127.0.0.1:7399/api/amsp/v1");
+ // Keyless access went on, so stderr carries the warning; stdout stays the status.
+ expect(err()).toContain(t.agent.apiOpenWarning());
+ expect(text).not.toContain(t.agent.apiOpenWarning());
+ });
+
+ it("disable sends only the switch: keyless access and the mode stay as they were", async () => {
+ await cli(["agent", "api", "enable", "--agent-id", "default_agent", "--open"]);
+ server.requests.length = 0;
+ expect(await cli(["agent", "api", "disable", "--agent-id", "default_agent"])).toBe(0);
+ expect(writes()).toEqual([["PUT", API, { enabled: false }]]);
+ expect(server.agentApi.get(REF)).toMatchObject({ enabled: false, open: true });
+ });
+
+ it("set sends only what it is given; given nothing it sends nothing and fails", async () => {
+ expect(await cli(["agent", "api", "set", "--agent-id", "default_agent", "--no-open"])).toBe(0);
+ expect(writes()).toEqual([["PUT", API, { open: false }]]);
+ expect(err()).not.toContain(t.agent.apiOpenWarning());
+
+ server.requests.length = 0;
+ expect(await cli(["agent", "api", "set", "--agent-id", "default_agent"])).toBe(1);
+ expect(err()).toContain(t.agent.apiNothingToSet());
+ expect(server.requests).toEqual([]);
+ });
+
+ it("an unknown approval mode fails before any request", async () => {
+ const exit = vi.spyOn(process, "exit").mockImplementation(() => {
+ throw new Error("exit");
+ });
+ try {
+ expect(
+ await cli(["agent", "api", "enable", "--agent-id", "default_agent", "--approve", "ask"]),
+ ).toBe(1);
+ } finally {
+ exit.mockRestore();
+ }
+ expect(err()).toContain(t.approveModeInvalid("ask"));
+ expect(server.requests).toEqual([]);
+ });
+
+ it("never picks the agent by default: without --agent-id nothing is sent", async () => {
+ expect(await cli(["agent", "api", "enable"])).toBe(1);
+ expect(server.requests).toEqual([]);
+ });
+});
+
+describe("penguin agent api status / server", () => {
+ it("status shows the server switch to a member who is not an admin, without asking the admin settings", async () => {
+ server.adminSettings = { ...server.adminSettings, agentApiEnabled: false };
+ server.adminForbidden = true;
+ expect(await cli(["agent", "api", "status", "--agent-id", "default_agent"])).toBe(0);
+ expect(out()).toMatch(new RegExp(`${t.agent.apiFieldServer()}\\s+off`));
+
+ stdout.length = 0;
+ expect(await cli(["agent", "api", "status", "--agent-id", "default_agent", "--json"])).toBe(0);
+ expect(JSON.parse(out())).toEqual({
+ agent: REF,
+ baseUrl: "http://127.0.0.1:7399/api/amsp/v1",
+ api: { enabled: false, open: false, approvalMode: "allow-all", keys: [] },
+ serverEnabled: false,
+ });
+ expect(server.requests.some((r) => r.path === "/api/admin/settings")).toBe(false);
+ });
+
+ it("server off and on write the server-wide switch", async () => {
+ expect(await cli(["agent", "api", "server", "off"])).toBe(0);
+ expect(out()).toBe(`${t.agent.apiServerSet(false)}\n`);
+ expect(await cli(["agent", "api", "server", "on", "--json"])).toBe(0);
+ expect(writes()).toEqual([
+ ["PUT", "/api/admin/settings", { agentApiEnabled: false }],
+ ["PUT", "/api/admin/settings", { agentApiEnabled: true }],
+ ]);
+ expect(out()).toContain(`{"agentApiEnabled":true}`);
+ });
+
+ it("server with any other state sends nothing", async () => {
+ expect(await cli(["agent", "api", "server", "maybe"])).toBe(1);
+ expect(err()).toContain(t.agent.apiServerStateInvalid("maybe"));
+ expect(server.requests).toEqual([]);
+ });
+});
+
+describe("penguin agent api: the credential a request carries", () => {
+ const BOOT_TOKEN = "boot-token-1";
+ const LOGIN = "login-token-1";
+ const asCookie = { cookie: `penguin_session=${LOGIN}` };
+ const asBearer = { authorization: `Bearer ${BOOT_TOKEN}` };
+ /** The token file the server writes at every boot, in the data root the fake pins. */
+ const writeTokenFile = () =>
+ fs.writeFileSync(path.join(process.env.ADELIE_HOME!, "api-token"), `${BOOT_TOKEN}\n`);
+ /** `penguin auth login` against `target`: the stored sign-in, which the fake accepts. */
+ const signIn = (target = "http://localhost:7399") => {
+ writeSession(process.env.ADELIE_HOME!, { server: target, userId: "admin", token: LOGIN });
+ server.logins.add(LOGIN);
+ };
+ const credentials = () => server.requests.map((r) => r.credential);
+ const state = () => JSON.stringify([[...server.agentApi], server.adminSettings]);
+ const WRITES = [
+ [["enable", "--agent-id", "default_agent", "--open"]],
+ [["disable", "--agent-id", "default_agent"]],
+ [["set", "--agent-id", "default_agent", "--approve", "read-only"]],
+ [["keys", "create", "--agent-id", "default_agent", "--name", "ci"]],
+ [["keys", "rm", "key1", "--agent-id", "default_agent"]],
+ [["server", "on"]],
+ ];
+
+ it("sends the token file as Bearer, a stored sign-in notwithstanding, wherever the server takes the token", async () => {
+ writeTokenFile();
+ signIn();
+ for (const argv of [
+ ["agent", "ls"],
+ ["agent", "api", "status", "--agent-id", "default_agent"],
+ ["agent", "api", "keys", "ls", "--agent-id", "default_agent"],
+ ]) {
+ expect(await cli(argv), argv.join(" ")).toBe(0);
+ }
+ expect(credentials()).toEqual([asBearer, asBearer, asBearer]);
+ });
+
+ it("retries a write refused human_required once as the stored sign-in, alone as the session cookie, and the write goes through", async () => {
+ writeTokenFile();
+ signIn();
+ for (const argv of [
+ ["agent", "api", "enable", "--agent-id", "default_agent", "--open"],
+ ["agent", "api", "keys", "create", "--agent-id", "default_agent", "--name", "ci"],
+ ["agent", "api", "keys", "rm", "key1", "--agent-id", "default_agent"],
+ ["agent", "api", "server", "off"],
+ ]) {
+ expect(await cli(argv), argv.join(" ")).toBe(0);
+ }
+ expect(credentials()).toEqual([1, 2, 3, 4].flatMap(() => [asBearer, asCookie]));
+ expect(server.agentApi.get(REF)).toMatchObject({ enabled: true, open: true, keys: [] });
+ expect(server.adminSettings.agentApiEnabled).toBe(false);
+ });
+
+ it.each(WRITES)(
+ "with no stored sign-in, %j prints the sign-in hint, exits 1 and changes nothing",
+ async (argv) => {
+ writeTokenFile();
+ const before = state();
+ expect(await cli(["agent", "api", ...argv])).toBe(1);
+ expect(err()).toBe(`${t.agent.apiSignInRequired()}\n`);
+ expect(out()).toBe("");
+ expect(credentials()).toEqual([asBearer]);
+ expect(state()).toBe(before);
+ },
+ );
+
+ it.each([
+ [
+ "inside a Session",
+ () => {
+ process.env.ADELIE_SESSION_ID = "session-2026-10-09-10-00-00-5e55a001";
+ signIn();
+ },
+ ],
+ ["for a sign-in to another server", () => signIn("https://penguin.example")],
+ ])(
+ "%s, the stored sign-in is never sent: the write prints the hint and exits 1",
+ async (_case, arrange) => {
+ writeTokenFile();
+ arrange();
+ const before = state();
+ expect(await cli(["agent", "api", "enable", "--agent-id", "default_agent", "--open"])).toBe(
+ 1,
+ );
+ expect(err()).toBe(`${t.agent.apiSignInRequired()}\n`);
+ expect(credentials()).toEqual([asBearer]);
+ expect(state()).toBe(before);
+ },
+ );
+
+ it("a stored sign-in the server no longer accepts leaves the refusal: the hint, exit 1", async () => {
+ writeTokenFile();
+ signIn();
+ server.logins.clear();
+ const before = state();
+ expect(await cli(["agent", "api", "enable", "--agent-id", "default_agent", "--open"])).toBe(1);
+ expect(err()).toBe(`${t.agent.apiSignInRequired()}\n`);
+ expect(credentials()).toEqual([asBearer, asCookie]);
+ expect(state()).toBe(before);
+ });
+});
diff --git a/packages/cli/test/fake-server.ts b/packages/cli/test/fake-server.ts
index ced038b9..c10c3cf7 100644
--- a/packages/cli/test/fake-server.ts
+++ b/packages/cli/test/fake-server.ts
@@ -2,12 +2,17 @@
* In-process fake Adelie server for CLI tests: stubs `globalThis.fetch` with a
* handler covering exactly the endpoints the server-backed commands touch (the current
* user, session create/get/patch, tasks/steer/compact/switch-model/abort, SSE stream,
- * messages, agents, projects, usage, schedules, organizations and their channels, the
- * admin storage report the `storage` field holds, and — through
+ * messages, agents and their public API settings, projects, usage, schedules, the admin settings,
+ * organizations and their channels, the admin storage report the `storage` field holds, and — through
* the `builtinBrowser` handler a test sets — the built-in browser). Connection resolution is pinned via ADELIE_API_URL
- * (a loopback URL, so no token gate) and PENGUIN_HOME points at a scratch directory so
+ * (a loopback URL, so no token gate) and ADELIE_HOME points at a scratch directory so
* nothing of the developer's real data root is read.
*
+ * Credentials, as the server reads them: a request without one is let through (the token gate
+ * above); a Bearer header is the local API token, which the agent API writes and the admin's
+ * `agentApiEnabled` refuse with 403 `human_required`; a `penguin_session` cookie is a sign-in,
+ * accepted only when it is one of `logins` (401 otherwise). Each request records what it sent.
+ *
* The SSE stream is real: a ReadableStream whose frames follow the server's wire shape
* (default-event OmniMessage frames, `event: server_event` control frames, incrementing
* ids). A task POST synchronously emits `task_state running`, the script's messages,
@@ -103,6 +108,14 @@ export interface FakeOrgState {
unpriced: boolean;
}
+/** One agent's public API settings: the management DTO's shape, keys included. */
+export interface FakeAgentApiState {
+ enabled: boolean;
+ open: boolean;
+ approvalMode: string;
+ keys: Json[];
+}
+
/** Who a fake request is attributed to, or the error response that settles it. */
type FakeCaller =
| { ok: true; principal: string; agentId: string | null; sessionId?: string }
@@ -182,8 +195,19 @@ const isNonEmptyString = (value: unknown): value is string =>
typeof value === "string" && value !== "";
export class FakeServer {
- /** Every request, in order: the path without its query, the query on its own, and the parsed body. */
- readonly requests: Array<{ method: string; path: string; search: string; body?: Json }> = [];
+ /**
+ * Every request, in order: the path without its query, the query on its own, the parsed body,
+ * and the credential it carried (`authorization` / `cookie`, each only when sent).
+ */
+ readonly requests: Array<{
+ method: string;
+ path: string;
+ search: string;
+ body?: Json;
+ credential?: { authorization?: string; cookie?: string };
+ }> = [];
+ /** Sign-in tokens a `penguin_session` cookie is accepted with; any other cookie is a 401. */
+ readonly logins = new Set<string>();
readonly sessions = new Map<string, FakeSessionState>();
agents: Array<Json> = [
{
@@ -273,6 +297,30 @@ export class FakeServer {
readonly scheduleItems = new Map<string, Json>();
/** Company mode: organizations keyed by org id. */
readonly orgs = new Map<string, FakeOrgState>();
+ /**
+ * Each agent's public API settings, keyed `<projectId>/<agentId>`; an agent missing here reads
+ * as the server reads one never configured (off, keyed, allow-all, no keys).
+ */
+ readonly agentApi = new Map<string, FakeAgentApiState>();
+ /**
+ * What GET /api/admin/settings answers. Its `agentApiEnabled` is also every agent API settings
+ * answer's `serverEnabled`, which any member reads.
+ */
+ adminSettings: Json = {
+ proxyForApp: true,
+ proxyForAgent: true,
+ proxyUrl: null,
+ attachmentMaxMb: 100,
+ attachmentTotalMb: 120,
+ companyMode: false,
+ browserExtensionsEnabled: true,
+ agentApiEnabled: true,
+ };
+ /** The admin settings routes answer 403, as for an account that is not an admin. */
+ adminForbidden = false;
+ /** Every secret POST …/api/keys minted, in order: short and obviously fake, never key-shaped. */
+ readonly mintedSecrets: string[] = [];
+ private nextKeyOrdinal = 1;
/**
* The built-in browser (`/api/builtin-browser/*`): answers each request from its method, its
* path below that prefix, its query and its body. The default is what a server outside the
@@ -336,7 +384,7 @@ export class FakeServer {
for (const key of [
"ADELIE_API_URL",
"ADELIE_API_TOKEN",
- "PENGUIN_HOME",
+ "ADELIE_HOME",
"ADELIE_SESSION_ID",
"ADELIE_PROJECT_ID",
"ADELIE_AGENT_ID",
@@ -345,7 +393,7 @@ export class FakeServer {
this.savedEnv.set(key, process.env[key]);
}
this.scratch = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-cli-test-"));
- process.env.PENGUIN_HOME = this.scratch;
+ process.env.ADELIE_HOME = this.scratch;
process.env.ADELIE_API_URL = "http://127.0.0.1:7399";
delete process.env.ADELIE_API_TOKEN;
delete process.env.ADELIE_SESSION_ID;
@@ -439,6 +487,65 @@ export class FakeServer {
return this.error(400, "bad_request", message);
}
+ /** The server's refusal of the local API token on a write only a person may make. */
+ private humanRequired(): Response {
+ return this.error(
+ 403,
+ "human_required",
+ "Only the signed-in user can do this, in the app; an API token cannot.",
+ );
+ }
+
+ // ---- an agent's public API ----
+
+ private handleAgentApi(
+ method: string,
+ ref: string,
+ isKeys: boolean,
+ keyId: string | undefined,
+ body: Json | undefined,
+ ): Response {
+ let api = this.agentApi.get(ref);
+ if (!api) {
+ api = { enabled: false, open: false, approvalMode: "allow-all", keys: [] };
+ this.agentApi.set(ref, api);
+ }
+ if (!isKeys) {
+ if (method === "PUT") {
+ if (typeof body?.enabled === "boolean") api.enabled = body.enabled;
+ if (typeof body?.open === "boolean") api.open = body.open;
+ if (typeof body?.approvalMode === "string") api.approvalMode = body.approvalMode;
+ }
+ return this.json({ api, serverEnabled: this.adminSettings.agentApiEnabled !== false });
+ }
+ if (keyId === undefined && method === "POST") {
+ const name = typeof body?.name === "string" ? body.name.trim() : "";
+ if (name.length < 1 || name.length > 64) return this.badRequest("name is 1-64 characters.");
+ const n = this.nextKeyOrdinal++;
+ const secret = `penguin_fake-${n}`;
+ this.mintedSecrets.push(secret);
+ const key = {
+ keyId: `key${n}`,
+ name,
+ prefix: secret.slice(0, 12),
+ createdBy: this.userId,
+ createdAt: "2026-10-07T10:00:00.000Z",
+ lastUsedAt: null,
+ };
+ api.keys.push(key);
+ return this.json({ key, secret }, 201);
+ }
+ if (keyId !== undefined && method === "DELETE") {
+ const kept = api.keys.filter((k) => k.keyId !== keyId);
+ if (kept.length === api.keys.length) {
+ return this.error(404, "key_not_found", `No key ${keyId}.`);
+ }
+ api.keys = kept;
+ return new Response(null, { status: 204 });
+ }
+ return this.error(404, "not_found", `No fake route for ${method} …/api/keys`);
+ }
+
// ---- company mode: state ----
/** Adds an organization whose CEO (`ceoAgentId`, default `ceo`) is its first employee; `overrides` win. */
@@ -1654,12 +1761,31 @@ export class FakeServer {
if (typeof init?.body === "string" && init.body.length > 0) {
body = JSON.parse(init.body) as Json;
}
+ const headers = new Headers(init?.headers);
+ const authorization = headers.get("authorization") ?? undefined;
+ const cookie = headers.get("cookie") ?? undefined;
this.requests.push({
method,
path: apiPath,
search: url.search,
...(body !== undefined ? { body } : {}),
+ ...(authorization !== undefined || cookie !== undefined
+ ? {
+ credential: {
+ ...(authorization !== undefined ? { authorization } : {}),
+ ...(cookie !== undefined ? { cookie } : {}),
+ },
+ }
+ : {}),
});
+ // The server reads a Bearer first; a cookie alone must be a sign-in it knows.
+ if (authorization === undefined && cookie !== undefined) {
+ const login = /(?:^|;\s*)penguin_session=([^;]+)/.exec(cookie)?.[1];
+ if (login === undefined || !this.logins.has(login)) {
+ return this.error(401, "unauthorized", "Not signed in or the sign-in has expired.");
+ }
+ }
+ const viaToken = authorization !== undefined;
if (apiPath.startsWith("/api/builtin-browser/")) {
const answer = this.builtinBrowser({
@@ -1798,6 +1924,28 @@ export class FakeServer {
});
}
+ // An agent's public API settings and keys
+ m = /^\/api\/projects\/([^/]+)\/agents\/([^/]+)\/api(\/keys(?:\/([^/]+))?)?$/.exec(apiPath);
+ if (m) {
+ if (viaToken && method !== "GET") return this.humanRequired();
+ return this.handleAgentApi(
+ method,
+ `${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`,
+ m[3] !== undefined,
+ m[4] === undefined ? undefined : decodeURIComponent(m[4]),
+ body,
+ );
+ }
+
+ if (apiPath === "/api/admin/settings") {
+ if (this.adminForbidden) return this.error(403, "forbidden", "Admins only.");
+ if (viaToken && method === "PUT" && body?.agentApiEnabled !== undefined) {
+ return this.humanRequired();
+ }
+ if (method === "PUT") this.adminSettings = { ...this.adminSettings, ...body };
+ return this.json({ settings: this.adminSettings });
+ }
+
m = /^\/api\/projects\/([^/]+)\/usage$/.exec(apiPath);
if (m) {
const groupBy = url.searchParams.get("groupBy") ?? "date";
diff --git a/packages/docs/content/agent-api.en.md b/packages/docs/content/agent-api.en.md
new file mode 100644
index 00000000..dac5d609
--- /dev/null
+++ b/packages/docs/content/agent-api.en.md
@@ -0,0 +1,336 @@
+---
+title: Agent API
+description: Let a program talk to one agent over HTTP — turn on the agent's API, mint keys, and run it with curl or the @lmliheng/amsp client.
+---
+
+The Agent API lets a program outside PenguinHarness — a script, a service, a page in a browser — talk to one agent over HTTP. The program sends its input, reads the run as it happens as an [AMSP](/amsp) event stream, and continues the conversation by its Session id. A run uses the Project's models and credentials, is recorded like any other conversation, and appears in the sidebar's **Background** folder.
+
+Where to go:
+
+- To expose an agent, see [Turn on an agent's API](#turn-on-an-agents-api).
+- To try it from a shell, see [Call it with curl](#call-it-with-curl).
+- To call it from TypeScript, in Node or a browser, see [The amsp client](#the-amsp-client).
+- For the event stream itself, event by event, see [AMSP](/amsp).
+
+## Before you begin
+
+- Only the Project's owner turns an agent's API on or off, chooses its approval mode and manages its keys. Members see the settings.
+- The server's administrator can turn the whole Agent API off; it is on by default. See [The admin switch](#the-admin-switch).
+- A program needs three things, all shown on the agent's **API** tab:
+ - the **Base URL**, the server's address followed by `/api/amsp/v1`, such as `http://localhost:7364/api/amsp/v1` for a local server. On a server bound to loopback, which is the default, the address is `localhost`: `127.0.0.1` is where it serves previews, and it answers every API request there with `401`;
+ - the **Agent ID**, `<projectId>/<agentId>`, such as `demo/coder`;
+ - a **key**, unless the agent allows [keyless access](#keyless-access).
+
+## Turn on an agent's API
+
+1. Open the agent's settings (see [Agent settings](/agents#agent-settings)) and select the **API** tab, at `/agents/<agentId>?tab=api`.
+2. Turn on **Enable API access**.
+3. Choose the **Approval mode for API conversations**. See [Approval mode](#approval-mode).
+4. Under **Keys**, select **New key**, name it and copy the key. It is shown once.
+5. Copy the **Base URL** and the **Agent ID** under **Connection**. **Examples** holds a curl command and a TypeScript snippet with both filled in and `$PENGUIN_AGENT_KEY` in place of the key.
+
+On the **Agents** page, an agent whose API is on carries an API icon after its name, with the tooltip **API access on**.
+
+Turning **Enable API access** off refuses every request for the agent at once with `404` `agent_not_found`. Its keys and settings are kept for when it is turned back on.
+
+These settings are stored by the server, outside the agent's state, so an agent can neither expose itself nor loosen its own approval mode.
+
+Changing them also takes a person's sign-in. The commands an agent runs carry the server's local API token: it reads these settings, but every change and **Try it** answer it `403` `human_required`, and so does the [admin switch](#the-admin-switch). This narrows what an agent can do from its own shell; it is not a boundary. A process that runs as the server's OS account outside the sandbox can still sign itself in, so what bounds an agent is its [sandbox](/settings#sandbox).
+
+### Approval mode
+
+API conversations have their own approval mode, separate from the one the composer preselects:
+
+| Mode | In the selector | What the calling program sees |
+| --- | --- | --- |
+| `allow-all` (default) | **Approve everything** | Every tool call runs; nothing waits on the caller |
+| `read-only` | **Approve read-only** | Read-only tools run; every other call is sent to the caller as `approval.requested` and waits for an answer |
+| `always-ask` | **Ask every time** | Every tool call waits for the caller's answer |
+| `deny-all` | **Deny everything** | Every tool call is denied; the model reads the denial and carries on without it |
+
+- The mode is read when an API conversation is created and stays with that conversation. A change on the tab applies to API conversations created afterwards. To change one existing conversation, open it in the Web App and change its approval mode there.
+- A call that waits is sent to the caller and shown in the conversation in the Web App as well; whichever answers first decides. The run waits with no time limit: until an answer, an abort, or the caller disconnecting, which denies it.
+- `allow-all` is the default because the sandbox already bounds what the agent can do, and a program usually has no one to ask. Choose `read-only` or `always-ask` when the program answers approvals; see [Approvals](#approvals).
+
+An API conversation's sandbox comes from the server's new-chat defaults, as for any new conversation. The Project's preselected approval mode for new conversations does not apply to it.
+
+### Keys
+
+- A key is `penguin_` followed by 43 characters. It is shown once, when it is created; the server stores only its SHA-256.
+- An agent can have several keys, each with a name. The list shows each key's name, its first characters, when it was created and when it was last used (**never** until its first run).
+- Deleting a key revokes it: the next request that presents it is refused with `401`.
+- A key belongs to one agent. It runs that agent and reads, aborts and answers the approvals of that agent's API conversations, and opens nothing else on the server. A key of another agent is refused with `404` `agent_not_found`.
+- Send it as `Authorization: Bearer <key>`.
+
+### Keyless access
+
+**Allow keyless access** lets a request without a key run the agent. It is off by default, and a request that presents a key is still checked while it is on. Switching it on asks first, with the warning below; `penguin agent api enable --open` and `set --open` print the same warning on stderr once it is on.
+
+> [!WARNING]
+> With keyless access on, anything that can reach the server's address can talk to the agent, with the Project's models and credentials. Turn it on only for a server that listens on loopback (`127.0.0.1`).
+
+A browser page on another origin cannot use keyless access: the server sends no CORS header on a request without `Authorization`. See [In a browser](#in-a-browser).
+
+### Try it
+
+The **API** tab ends, for the Project's owner, with **Try it**: an input holding "What time is it now?" and **Run**. **Run** sends one real API run through `POST /api/projects/:projectId/agents/:agentId/api/try`, your sign-in standing in for a key and the same handler behind it, and shows the stream a program would receive in one output box. The box's header names the run's `session_id` and switches between two views: **Rendered**, one numbered row per item or event, with an item's fragments merged into the content they add up to (the answer, a tool call and its arguments, the tool's output), and **Raw**, one numbered line per `data:` payload exactly as received. The strip under them gives the `run.done` status with the Request count, tokens and elapsed time. The default agent can tell the time only by running `date`, so the example shows a tool call and its result. Running again continues the conversation, as a program does with `session_id`; **New conversation** starts another. **Stop** aborts the run through the Session's abort route, so the stream still ends with `run.done`, and when the approval mode asks, **Allow** and **Deny** appear on the `approval.requested` row. The conversation is an ordinary API conversation, filed in the **Background** folder. While the administrator has the Agent API off, **Run** is disabled.
+
+## Call it with curl
+
+```bash
+curl -N http://localhost:7364/api/amsp/v1/agents/demo/coder/runs \
+ -H "Authorization: Bearer $PENGUIN_AGENT_KEY" -H "Content-Type: application/json" \
+ -d '{"input":"Summarize README.md"}'
+```
+
+The answer is the run, streamed as it happens: one `data:` line per event, then `data: [DONE]`. `-N` turns off curl's buffering so events print as they arrive. The first event, `run.started`, names the Session; the last, `run.done`, says how the run ended and what it counted:
+
+```text
+data: {"type":"run.started","at":"2026-10-07T10:00:00.000Z","session_id":"session-2026-10-07-10-00-00-3f9a1c2e","agent":"demo/coder"}
+data: {"type":"request.started","at":"…","request":1}
+data: {"type":"text.delta","at":"…","role":"assistant","text":"README.md describes"}
+…
+data: {"type":"run.done","at":"…","status":"completed","requests":1,"usage":{…},"session_usage":{…}}
+data: [DONE]
+```
+
+To continue the conversation, send the Session id with the next input:
+
+```bash
+curl -N http://localhost:7364/api/amsp/v1/agents/demo/coder/runs \
+ -H "Authorization: Bearer $PENGUIN_AGENT_KEY" -H "Content-Type: application/json" \
+ -d '{"session_id":"session-2026-10-07-10-00-00-3f9a1c2e","input":"Now list its headings"}'
+```
+
+## Routes
+
+All paths are relative to the Base URL. A path under it that matches no route is answered `404` `not_found` in JSON.
+
+| Method | Path | Answer |
+| --- | --- | --- |
+| GET | `/agents/:projectId/:agentId` | `{agent: {id, name?, description?}}` |
+| POST | `/agents/:projectId/:agentId/runs` | The run as an event stream; see [AMSP](/amsp) |
+| GET | `/sessions/:sessionId` | `{session: {id, agent, status, provider, model_id, created_at, last_active_at}}` |
+| POST | `/sessions/:sessionId/abort` | `202` when a run was interrupted, `204` when none was running |
+| POST | `/sessions/:sessionId/approvals/:toolCallId` | `{decision: "allow" \| "deny"}`; `204`, or `404` `approval_not_found` when it was already answered |
+
+The API tab and `penguin agent api` manage the settings through `/api/projects/:projectId/agents/:agentId/api` and its `keys` routes, signed in as the Project's owner; see [Server API](/server-api).
+
+### The run request
+
+```ts
+interface RunRequest {
+ session_id?: string; // continue this conversation; omit to start one
+ input: string | InputItem[];
+}
+type InputItem =
+ | { type: "text"; text: string }
+ | { type: "image_url"; image_url: string }; // a data: URL, or an http(s) URL
+```
+
+- `input` must carry a non-empty text or an image.
+- An image is a `data:` URL of an image type, within the 20 MB inline-image cap and the server's attachment total, or an `http(s)` URL, which goes to the model as it is. Files are not accepted.
+- Without `session_id`, the run starts a new conversation and `run.started` names it. With it, the run continues that conversation, which must be an API conversation of the same agent; any other id is `404` `session_not_found`.
+
+### Conversations
+
+- A new API conversation uses the Project's default model, the server's new-chat sandbox and the agent's API approval mode. Its title is generated from the first input, and its usage and cost count toward the Project, as for any conversation.
+- The sidebar lists API conversations in the agent's **Background** folder, each marked with the API icon. You can open one, read it, answer its approvals and type into it.
+- A conversation runs one thing at a time: a run on a conversation that is still working is refused with `409`. An agent runs at most four API runs at once; the fifth is refused with `429` and `Retry-After: 2`.
+- Disconnecting aborts the run. To stop a run and still receive how it ended, `POST /sessions/:sessionId/abort`: the stream stays open and ends with `run.done` and `status: "aborted"`.
+
+### Errors
+
+A request refused before the stream starts gets an HTTP status and one envelope, `{"error": {"code": "<code>", "message": "<text>"}}`:
+
+| Status | `code` | When |
+| --- | --- | --- |
+| 400 | `bad_request` | The body is not a JSON object; `input` is missing or empty; an item has an unknown `type`; `session_id` is not a valid id; an image is too large or not an image; `decision` is not `allow` or `deny` |
+| 401 | `unauthorized` | The agent needs a key and none, or an unknown one, was presented. Checked before the body is read |
+| 403 | `agent_api_disabled` | The administrator turned the Agent API off |
+| 404 | `agent_not_found` | No such agent, its API is off, or the key belongs to another agent |
+| 404 | `session_not_found` | No such Session, it is not an API conversation, or it belongs to another agent |
+| 404 | `approval_not_found` | The approval was already answered, or never existed |
+| 404 | `not_found` | No route at this path |
+| 409 | `task_in_progress`, `compacting` | The conversation is busy |
+| 413 | `payload_too_large` | The body exceeds the server's request size cap |
+| 415 | `unsupported_media_type` | A write without `Content-Type: application/json` |
+| 429 | `too_many_runs` | The agent already has four runs going; retry after `Retry-After` seconds |
+| 503 | as the server sends it | The server is shutting down, or the agent or conversation is being deleted |
+
+Once the stream has started, an error is never a separate frame: the run ends with `run.done`, whose `status` and `error` say what happened. See [Errors in the stream](/amsp#errors-in-the-stream).
+
+## The amsp client
+
+`@lmliheng/amsp` is the TypeScript client of the Agent API. It has no dependencies, runs in Node 24 and in current browsers, and exports the AMSP event types.
+
+```bash
+npm install @lmliheng/amsp
+```
+
+```ts
+import { AgentClient } from "@lmliheng/amsp";
+
+const client = new AgentClient({
+ baseUrl: "http://localhost:7364/api/amsp/v1",
+ agent: "demo/coder",
+ apiKey: process.env.PENGUIN_AGENT_KEY,
+});
+
+const run = client.run({ input: "Summarize README.md" });
+for await (const event of run) {
+ if (event.type === "text.delta") process.stdout.write(event.text);
+}
+const first = await run.result();
+
+const second = await client.ask({
+ sessionId: first.sessionId,
+ input: "Now list its headings",
+ onApproval: () => "allow",
+});
+console.log(second.text, second.usage.total);
+```
+
+- `client.run()` starts the run at once and returns it. Iterate it for the events as they arrive — once; events are kept until read. `run.session` resolves with the Session id as soon as `run.started` arrives.
+- `run.result()` resolves when the stream ends, with `status`, `error`, `sessionId`, `text`, `items`, `usage`, `sessionUsage` and `requests`. `text` is the main conversation's assistant answers joined with a blank line; a subagent's texts, user messages and compaction summaries stay out of it. `items` holds every event except the `.delta` fragments, in order.
+- `client.ask()` runs to the end and returns the same result, keeping nothing for iteration.
+- Leaving the loop early stops the iteration, not the run: approvals are still answered and `result()` still resolves. To stop the run, see [Aborting](#aborting).
+- An event type the client does not know is passed through, so switch on `event.type` with a default branch.
+
+### Approvals
+
+When the approval mode makes a call wait, the run delivers `approval.requested` and the client answers it for you: with `onApproval`'s decision, or `deny` when there is no callback or it throws. It answers whether you iterate or only await the result.
+
+```ts
+import { AgentClient, parseArguments } from "@lmliheng/amsp";
+
+const result = await client.ask({
+ input: "Clean up the build output",
+ onApproval: (request) => {
+ const args = parseArguments(request.tool_call);
+ return request.tool_call.name === "exec_command" && args?.command === "ls" ? "allow" : "deny";
+ },
+});
+```
+
+- `parseArguments` turns a tool call's arguments, which AMSP carries as the JSON string the model wrote, into an object: `{}` for none, `null` when they do not parse to an object.
+- An approval someone already answered in the Web App is not an error. An answer the server refuses, such as with a key deleted mid-run, ends the run with that `AmspHttpError`, closing the connection so the server aborts the run rather than wait for good.
+- `client.approve(sessionId, toolCallId, decision)` answers one by hand, for a program that reads the stream itself.
+
+### Aborting
+
+- Abort the `signal` passed to `run()` or `ask()` to drop the connection: the server aborts the run, and the run rejects with the signal's reason, an `AbortError` by default. Events not yet read are dropped.
+- `run.abort()` asks the server to abort and keeps the connection: the stream ends with `run.done` and `status: "aborted"`, and `result()` resolves with it.
+- `client.abort(sessionId)` does the same for a conversation by id, and returns whether a run was interrupted.
+
+### When a run fails
+
+- `result()` resolves for every run that reached `run.done`, whatever its `status`; check `status` and `error`.
+- A refusal before the stream rejects with `AmspHttpError`, carrying `status`, `code` and `message` from the envelope. A body that is not the envelope gives `code: "http_error"` and a message with the status and the start of the body.
+- A stream that ends or breaks before `run.done`, or carries a block that is not an AMSP event, rejects with `AmspStreamError`: the run's outcome is unknown, and `client.session(sessionId)` tells whether it is still running.
+- A network failure and an abort reject as `fetch` raised them.
+
+### In a browser
+
+The same package works in a browser through a bundler. A page on another origin than the server needs a key: the server answers the CORS preflight for any origin, but sends `Access-Control-Allow-Origin: *` only on a request carrying `Authorization`. A cross-origin request may carry only `Authorization` and `Content-Type`, so extra `headers` are for same-origin pages and Node.
+
+```ts
+import { AgentClient } from "@lmliheng/amsp";
+
+const keyField = document.querySelector<HTMLInputElement>("#key")!;
+const client = new AgentClient({
+ baseUrl: "http://localhost:7364/api/amsp/v1",
+ agent: "demo/coder",
+ apiKey: keyField.value,
+});
+
+const answer = document.querySelector("#answer")!;
+for await (const event of client.run({ input: "What changed today?" })) {
+ if (event.type === "text.delta") answer.textContent += event.text;
+}
+```
+
+> [!WARNING]
+> A key in a page is readable by everyone who loads the page. Use a browser client for a tool only you and your team open, with the key entered at run time, or keep the key on a backend that calls the agent for the page.
+
+### Client reference
+
+```ts
+class AgentClient {
+ constructor(opts: {
+ baseUrl: string; // ".../api/amsp/v1"
+ agent: string; // "<projectId>/<agentId>"
+ apiKey?: string; // omitted = keyless; no environment variable is read
+ fetch?: typeof fetch; // the global fetch by default
+ headers?: Record<string, string>;
+ });
+ run(opts: RunOptions): Run;
+ ask(opts: RunOptions): Promise<RunResult>;
+ agent(): Promise<AgentInfo>;
+ session(sessionId: string): Promise<SessionInfo>;
+ abort(sessionId: string): Promise<boolean>;
+ approve(sessionId: string, toolCallId: string, decision: "allow" | "deny"): Promise<void>;
+}
+
+interface RunOptions {
+ input: string | InputItem[];
+ sessionId?: string;
+ signal?: AbortSignal;
+ onApproval?: (
+ request: ApprovalRequested,
+ ctx: { sessionId: string },
+ ) => "allow" | "deny" | Promise<"allow" | "deny">;
+}
+
+interface Run extends AsyncIterable<AmspEvent> {
+ readonly session: Promise<string>;
+ result(): Promise<RunResult>;
+ abort(): Promise<void>;
+}
+
+interface RunResult {
+ status: "completed" | "aborted" | "retryable" | "fatal";
+ error?: { code: string; message: string };
+ sessionId: string;
+ text: string;
+ items: AmspEvent[];
+ usage: TokenCounts;
+ sessionUsage: TokenCounts | null;
+ requests: number;
+}
+
+function parseArguments(call: { arguments: string }): Record<string, unknown> | null;
+function readSse(body: ReadableStream<Uint8Array>): AsyncGenerator<string>;
+class RunCollector {
+ add(event: AmspEvent): void;
+ readonly finished: boolean; // run.done has arrived
+ result(): RunResult; // throws AmspStreamError before run.done
+}
+class AmspHttpError extends Error { status: number; code: string }
+class AmspStreamError extends Error {}
+```
+
+`readSse` is the client's SSE reader, exported for a program that reads a run's body itself: it yields each event's data, `[DONE]` included. `RunCollector` folds the events such a program parses into the `RunResult` that `result()` returns.
+
+## From the command line
+
+`penguin agent api` manages an agent's API from a terminal, against the running server, with the same rules as the API tab:
+
+| Command | What it does |
+| --- | --- |
+| `penguin agent api status --agent-id <id>` | Shows whether the API is on, keyless access, the approval mode, the Base URL, the Agent ID, the number of keys and the admin switch |
+| `penguin agent api enable --agent-id <id> [--open \| --no-open] [--approve <mode>]` | Turns the API on, optionally setting keyless access and the approval mode |
+| `penguin agent api disable --agent-id <id>` | Turns the API off |
+| `penguin agent api set --agent-id <id> [--open \| --no-open] [--approve <mode>]` | Changes keyless access or the approval mode without turning the API on or off |
+| `penguin agent api keys ls --agent-id <id>` | Lists the keys: id, name, first characters, created, last used |
+| `penguin agent api keys create --agent-id <id> --name <name>` | Mints a key. The key alone goes to stdout, everything else to stderr, so `$(…)` captures just the key |
+| `penguin agent api keys rm <keyId> --agent-id <id>` | Deletes a key |
+| `penguin agent api server on\|off` | The admin switch |
+
+Each command also takes `--project-id`, `--server` and `--json`. `--approve` takes the four modes: `allow-all`, `read-only`, `always-ask`, `deny-all`. See the [CLI Reference](/cli).
+
+The commands that change something (`enable`, `disable`, `set`, `keys create`, `keys rm` and `server`) need your sign-in: run `penguin auth login` once, or `penguin auth token` on the server's machine. The server refuses them to the local API token, and the CLI then sends them again with that sign-in. Without it they print that hint and exit 1. `status` and `keys ls` need none.
+
+## The admin switch
+
+**Settings › Server › Agent API** holds the administrator's **Allow the Agent API** switch, on by default. Turning it off asks first, then refuses every Agent API request with `403` `agent_api_disabled`, the CORS preflight excepted. Agents' switches, approval modes and keys are kept, and every member sees the API tab's switch disabled with a note saying why. See [Agent API](/settings#agent-api) in Settings. The setting is `agentApiEnabled` in `GET`/`PUT /api/admin/settings`, and `penguin agent api server on|off` sets it from a terminal once you have signed in.
diff --git a/packages/docs/content/agent-api.zh.md b/packages/docs/content/agent-api.zh.md
new file mode 100644
index 00000000..254bba46
--- /dev/null
+++ b/packages/docs/content/agent-api.zh.md
@@ -0,0 +1,336 @@
+---
+title: Agent API
+description: 让外部程序经 HTTP 与某个 Agent 对话:开启 Agent 的 API、签发密钥,再用 curl 或 @lmliheng/amsp 客户端运行它。
+---
+
+Agent API 让 PenguinHarness 之外的程序(脚本、服务、浏览器里的页面)经 HTTP 与某一个 Agent 对话。程序发送输入,以 [AMSP](/amsp) 事件流实时读取这次运行,再凭 Session id 延续对话。运行使用 Project 的模型与凭据,像其他对话一样被记录,并出现在侧边栏的**后台会话**折叠夹中。
+
+从哪里开始:
+
+- 想对外开放某个 Agent,见[开启 Agent 的 API](#开启-agent-的-api)。
+- 想在 shell 里试一试,见[用 curl 调用](#用-curl-调用)。
+- 想在 TypeScript 里调用(Node 或浏览器),见 [amsp 客户端](#amsp-客户端)。
+- 想逐个了解事件流里的事件,见 [AMSP](/amsp)。
+
+## 开始之前
+
+- 只有 Project 的所有者能开启或关闭 Agent 的 API、选择审批模式、管理密钥;成员可以查看这些设置。
+- 服务器管理员可以整体关闭 Agent API,缺省为开启。见[管理员开关](#管理员开关)。
+- 程序需要三样东西,都显示在该 Agent 的 **API** 标签页上:
+ - **Base URL**:服务器地址加上 `/api/amsp/v1`,本机服务器即 `http://localhost:7364/api/amsp/v1`。服务器监听本机回环地址时(这是缺省设置),地址要写 `localhost`:`127.0.0.1` 是它提供预览的地址,在那里的所有 API 请求都以 `401` 拒绝;
+ - **Agent ID**:`<projectId>/<agentId>`,例如 `demo/coder`;
+ - **密钥**:除非该 Agent 允许[无密钥访问](#无密钥访问)。
+
+## 开启 Agent 的 API
+
+1. 打开该 Agent 的设置(见 [Agent 设置](/agents#agent-设置)),选择 **API** 标签页,地址为 `/agents/<agentId>?tab=api`。
+2. 打开**开启 API 访问**。
+3. 选择 **API 会话的审批模式**,见[审批模式](#审批模式)。
+4. 在**密钥**下选择**新建密钥**,起个名字,然后复制密钥。密钥只显示这一次。
+5. 在**连接**下复制 **Base URL** 和 **Agent ID**。**示例**里有一条 curl 命令和一段 TypeScript 代码,两者都已填好,密钥处写作 `$PENGUIN_AGENT_KEY`。
+
+在**智能体**页面上,已开启 API 的 Agent 名称后带有 API 图标,悬停提示为**已开启 API 访问**。
+
+关闭**开启 API 访问**后,该 Agent 的所有请求立即以 `404` `agent_not_found` 拒绝。它的密钥和设置都会保留,等重新开启时继续使用。
+
+这些设置由服务器保存,不在 Agent 的状态里,因此 Agent 既不能自行对外开放,也不能放宽自己的审批模式。
+
+修改这些设置还需要人的登录。Agent 运行的命令带着服务器的本地 API token:它能读取这些设置,但每一项修改和**试一试**都以 `403` `human_required` 拒绝它,[管理员开关](#管理员开关)也一样。这收窄了 Agent 在自己的 shell 里能做的事,但不是边界:在沙盒之外、以服务器所属操作系统账号运行的进程仍能自行登录,真正约束 Agent 的是它的[沙盒](/settings#沙盒)。
+
+### 审批模式
+
+API 会话有自己的审批模式,与新建对话时预选的审批模式互不相干:
+
+| 模式 | 选择器中的名称 | 调用方看到的情形 |
+| --- | --- | --- |
+| `allow-all`(缺省) | **全部放行** | 所有工具调用直接执行,不等调用方 |
+| `read-only` | **放行只读** | 只读工具直接执行;其余调用以 `approval.requested` 发给调用方,等待回答 |
+| `always-ask` | **总是询问** | 每次工具调用都等调用方回答 |
+| `deny-all` | **全部拒绝** | 所有工具调用都被拒绝;模型读到拒绝结果,在没有该工具的情况下继续 |
+
+- 审批模式在 API 会话创建时读取,此后随该会话保存。在标签页上修改,只影响之后新建的 API 会话。要修改某个已有会话,在 Web App 中打开它,在那里修改它的审批模式。
+- 等待审批的调用会发给调用方,同时显示在 Web App 的该会话中,以先回答的一方为准。运行没有等待时限:直到有人回答、运行被中止,或调用方断开连接(此时视为拒绝)。
+- 缺省为 `allow-all`,是因为沙箱已经限定了 Agent 能做的事,而程序通常没有人可问。如果程序会回答审批,就选 `read-only` 或 `always-ask`,见[审批](#审批)。
+
+API 会话的沙箱取自服务器的新对话默认值,与其他新对话相同。Project 为新对话预选的审批模式不适用于 API 会话。
+
+### 密钥
+
+- 密钥形如 `penguin_` 加 43 个字符,只在创建时显示一次;服务器只保存它的 SHA-256。
+- 一个 Agent 可以有多个密钥,各有名字。列表显示每个密钥的名字、开头几个字符、创建时间和最近使用时间(首次运行之前显示**从未**)。
+- 删除密钥即撤销它:此后出示它的请求以 `401` 拒绝。
+- 密钥只属于一个 Agent:它能运行该 Agent,能读取、中止该 Agent 的 API 会话并回答其审批,此外不能访问服务器上的任何东西。出示另一个 Agent 的密钥会以 `404` `agent_not_found` 拒绝。
+- 以 `Authorization: Bearer <key>` 发送。
+
+### 无密钥访问
+
+**允许无密钥访问**让不带密钥的请求也能运行该 Agent。它缺省关闭;开启后,带了密钥的请求仍会校验密钥。打开此开关前会先弹出确认,提示下面的风险;`penguin agent api enable --open` 与 `set --open` 开启后也会在 stderr 打印同样的警告。
+
+> [!WARNING]
+> 开启无密钥访问后,任何能访问服务器地址的程序都能与该 Agent 对话,用的是 Project 的模型和凭据。只在服务器只监听本机回环地址(`127.0.0.1`)时开启。
+
+其他来源的浏览器页面无法使用无密钥访问:服务器不会给不带 `Authorization` 的请求返回 CORS 头。见[在浏览器中](#在浏览器中)。
+
+### 试一试
+
+**API** 标签页的末尾为 Project 所有者提供**试一试**:输入框预填「现在几点了?」,旁边是**运行**。**运行**经 `POST /api/projects/:projectId/agents/:agentId/api/try` 发起一次真实的 API 运行,以你的登录身份代替密钥,背后是同一个处理器,并在一个输出框里按程序会收到的样子显示事件流。输出框的标题栏显示这次运行的 `session_id`,并可在两种视图间切换:**渲染**,每个条目或事件一行并编号,同一条目的增量片段合并为拼好的内容(回答、工具调用及其参数、工具的输出);**原始**,每个 `data:` 负载一行并编号,与收到的完全一致。下方一栏给出 `run.done` 的状态以及 Request 次数、Token 和用时。默认 Agent 只有执行 `date` 才能知道时间,所以这个示例里能看到一次工具调用和它的结果。再次运行即续接这个会话,正如程序传入 `session_id`;**新会话**另起一个。**停止**经会话的中止路由中止运行,事件流照样以 `run.done` 结束;审批模式需要询问时,`approval.requested` 那一行会出现**允许**和**拒绝**。开出的会话就是普通的 API 会话,归入**后台会话**折叠夹。管理员关闭 Agent API 期间,**运行**不可用。
+
+## 用 curl 调用
+
+```bash
+curl -N http://localhost:7364/api/amsp/v1/agents/demo/coder/runs \
+ -H "Authorization: Bearer $PENGUIN_AGENT_KEY" -H "Content-Type: application/json" \
+ -d '{"input":"Summarize README.md"}'
+```
+
+响应就是这次运行,实时流式返回:每个事件一行 `data:`,最后是 `data: [DONE]`。`-N` 关闭 curl 的缓冲,事件到达即打印。第一个事件 `run.started` 给出 Session;最后一个事件 `run.done` 说明运行如何结束、计了多少 Token:
+
+```text
+data: {"type":"run.started","at":"2026-10-07T10:00:00.000Z","session_id":"session-2026-10-07-10-00-00-3f9a1c2e","agent":"demo/coder"}
+data: {"type":"request.started","at":"…","request":1}
+data: {"type":"text.delta","at":"…","role":"assistant","text":"README.md describes"}
+…
+data: {"type":"run.done","at":"…","status":"completed","requests":1,"usage":{…},"session_usage":{…}}
+data: [DONE]
+```
+
+要延续对话,把 Session id 和下一条输入一起发送:
+
+```bash
+curl -N http://localhost:7364/api/amsp/v1/agents/demo/coder/runs \
+ -H "Authorization: Bearer $PENGUIN_AGENT_KEY" -H "Content-Type: application/json" \
+ -d '{"session_id":"session-2026-10-07-10-00-00-3f9a1c2e","input":"Now list its headings"}'
+```
+
+## 路由
+
+所有路径都相对于 Base URL。其下不匹配任何路由的路径,以 JSON 形式返回 `404` `not_found`。
+
+| 方法 | 路径 | 响应 |
+| --- | --- | --- |
+| GET | `/agents/:projectId/:agentId` | `{agent: {id, name?, description?}}` |
+| POST | `/agents/:projectId/:agentId/runs` | 以事件流返回这次运行,见 [AMSP](/amsp) |
+| GET | `/sessions/:sessionId` | `{session: {id, agent, status, provider, model_id, created_at, last_active_at}}` |
+| POST | `/sessions/:sessionId/abort` | 中断了运行时返回 `202`,没有运行时返回 `204` |
+| POST | `/sessions/:sessionId/approvals/:toolCallId` | `{decision: "allow" \| "deny"}`;返回 `204`,已被回答时返回 `404` `approval_not_found` |
+
+API 标签页和 `penguin agent api` 以 Project 所有者的身份,经 `/api/projects/:projectId/agents/:agentId/api` 及其 `keys` 路由管理这些设置,见 [Server API](/server-api)。
+
+### 运行请求
+
+```ts
+interface RunRequest {
+ session_id?: string; // continue this conversation; omit to start one
+ input: string | InputItem[];
+}
+type InputItem =
+ | { type: "text"; text: string }
+ | { type: "image_url"; image_url: string }; // a data: URL, or an http(s) URL
+```
+
+- `input` 至少要有一段非空文本或一张图片。
+- 图片可以是图片类型的 `data:` URL,大小不超过 20 MB 的内联图片上限和服务器的附件总量上限;也可以是 `http(s)` URL,原样交给模型。不接受文件。
+- 不带 `session_id` 时,运行开启一个新会话,由 `run.started` 给出其 id。带上它,运行就延续那个会话;它必须是同一个 Agent 的 API 会话,其他 id 一律返回 `404` `session_not_found`。
+
+### 会话
+
+- 新的 API 会话使用 Project 的默认模型、服务器的新对话沙箱和该 Agent 的 API 审批模式。标题由第一条输入生成,用量和费用计入 Project,与其他会话相同。
+- 侧边栏把 API 会话列在该 Agent 的**后台会话**折叠夹中,每行带 API 图标。你可以打开它、阅读、回答其审批,也可以在其中输入。
+- 一个会话同一时间只做一件事:会话仍在工作时发起的运行以 `409` 拒绝。一个 Agent 同时最多有四个 API 运行,第五个以 `429` 拒绝,并带 `Retry-After: 2`。
+- 断开连接即中止运行。要停止运行、同时仍能收到它的结局,就 `POST /sessions/:sessionId/abort`:事件流保持打开,以 `status: "aborted"` 的 `run.done` 结束。
+
+### 错误
+
+在事件流开始之前被拒绝的请求,得到一个 HTTP 状态码和统一的信封 `{"error": {"code": "<code>", "message": "<text>"}}`:
+
+| 状态码 | `code` | 场景 |
+| --- | --- | --- |
+| 400 | `bad_request` | 请求体不是 JSON 对象;`input` 缺失或为空;某项的 `type` 未知;`session_id` 不是合法 id;图片过大或不是图片;`decision` 不是 `allow` 或 `deny` |
+| 401 | `unauthorized` | 该 Agent 需要密钥,而请求没有出示或出示了未知的密钥。在读取请求体之前检查 |
+| 403 | `agent_api_disabled` | 管理员关闭了 Agent API |
+| 404 | `agent_not_found` | 没有这个 Agent、它的 API 未开启,或密钥属于另一个 Agent |
+| 404 | `session_not_found` | 没有这个 Session、它不是 API 会话,或它属于另一个 Agent |
+| 404 | `approval_not_found` | 该审批已被回答,或从未存在 |
+| 404 | `not_found` | 该路径没有路由 |
+| 409 | `task_in_progress`、`compacting` | 会话正忙 |
+| 413 | `payload_too_large` | 请求体超过服务器的大小上限 |
+| 415 | `unsupported_media_type` | 写请求没有带 `Content-Type: application/json` |
+| 429 | `too_many_runs` | 该 Agent 已有四个运行在进行;等 `Retry-After` 秒后重试 |
+| 503 | 以服务器返回为准 | 服务器正在关闭,或该 Agent、会话正在被删除 |
+
+事件流一旦开始,错误就不会以单独的帧出现:运行以 `run.done` 结束,由其 `status` 和 `error` 说明发生了什么。见[流中的错误](/amsp#流中的错误)。
+
+## amsp 客户端
+
+`@lmliheng/amsp` 是 Agent API 的 TypeScript 客户端。它没有任何依赖,可在 Node 24 和当前的浏览器中运行,并导出 AMSP 的事件类型。
+
+```bash
+npm install @lmliheng/amsp
+```
+
+```ts
+import { AgentClient } from "@lmliheng/amsp";
+
+const client = new AgentClient({
+ baseUrl: "http://localhost:7364/api/amsp/v1",
+ agent: "demo/coder",
+ apiKey: process.env.PENGUIN_AGENT_KEY,
+});
+
+const run = client.run({ input: "Summarize README.md" });
+for await (const event of run) {
+ if (event.type === "text.delta") process.stdout.write(event.text);
+}
+const first = await run.result();
+
+const second = await client.ask({
+ sessionId: first.sessionId,
+ input: "Now list its headings",
+ onApproval: () => "allow",
+});
+console.log(second.text, second.usage.total);
+```
+
+- `client.run()` 立即开始运行并返回它。迭代它即可按到达顺序取得事件,只能迭代一次;事件在被读取之前一直保留。`run.started` 一到,`run.session` 就以 Session id 兑现。
+- 事件流结束时 `run.result()` 兑现,内容为 `status`、`error`、`sessionId`、`text`、`items`、`usage`、`sessionUsage` 和 `requests`。`text` 是主会话中助手的回答,以空行连接;子 Agent 的文本、用户消息和压缩摘要都不计入。`items` 按顺序包含除 `.delta` 分片以外的全部事件。
+- `client.ask()` 运行到结束并返回同样的结果,不为迭代保留任何事件。
+- 提前退出循环只停止迭代,不停止运行:审批照常回答,`result()` 照常兑现。要停止运行,见[中止](#中止)。
+- 客户端不认识的事件类型会原样传出,所以对 `event.type` 分支时要留一个缺省分支。
+
+### 审批
+
+当审批模式让某次调用等待时,运行会给出 `approval.requested`,客户端替你回答:用 `onApproval` 的决定;没有回调或回调抛出异常时回答 `deny`。无论你是在迭代还是只等待结果,客户端都会回答。
+
+```ts
+import { AgentClient, parseArguments } from "@lmliheng/amsp";
+
+const result = await client.ask({
+ input: "Clean up the build output",
+ onApproval: (request) => {
+ const args = parseArguments(request.tool_call);
+ return request.tool_call.name === "exec_command" && args?.command === "ls" ? "allow" : "deny";
+ },
+});
+```
+
+- AMSP 把工具调用的参数作为模型写出的 JSON 字符串传送,`parseArguments` 把它转成对象:没有参数时为 `{}`,解析不成对象时为 `null`。
+- 已经有人在 Web App 里回答过的审批不算错误。服务器拒绝接受的回答(例如运行途中密钥被删除)会以那个 `AmspHttpError` 结束运行,并断开连接,让服务器中止运行,而不是一直等下去。
+- 自行读取事件流的程序可以用 `client.approve(sessionId, toolCallId, decision)` 手动回答。
+
+### 中止
+
+- 中止传给 `run()` 或 `ask()` 的 `signal` 会断开连接:服务器中止运行,运行以该 signal 的 reason(缺省为 `AbortError`)拒绝。尚未读取的事件被丢弃。
+- `run.abort()` 请服务器中止运行,并保持连接:事件流以 `status: "aborted"` 的 `run.done` 结束,`result()` 以它兑现。
+- `client.abort(sessionId)` 按 id 对某个会话做同样的事,并返回是否中断了运行。
+
+### 运行失败时
+
+- 只要运行到达了 `run.done`,无论其 `status` 如何,`result()` 都会兑现;请检查 `status` 和 `error`。
+- 事件流开始之前的拒绝以 `AmspHttpError` 拒绝,带有信封中的 `status`、`code` 和 `message`。响应体不是信封时,`code` 为 `http_error`,message 包含状态码和响应体的开头部分。
+- 事件流在 `run.done` 之前结束或中断,或带有不是 AMSP 事件的数据块时,以 `AmspStreamError` 拒绝:运行的结局未知,`client.session(sessionId)` 可以告诉你它是否仍在运行。
+- 网络故障和中止按 `fetch` 抛出的原样拒绝。
+
+### 在浏览器中
+
+同一个包经打包工具即可在浏览器中使用。与服务器不同源的页面必须使用密钥:服务器对任何来源都应答 CORS 预检,但只在带 `Authorization` 的请求上返回 `Access-Control-Allow-Origin: *`。跨源请求只能携带 `Authorization` 和 `Content-Type`,所以额外的 `headers` 只适用于同源页面和 Node。
+
+```ts
+import { AgentClient } from "@lmliheng/amsp";
+
+const keyField = document.querySelector<HTMLInputElement>("#key")!;
+const client = new AgentClient({
+ baseUrl: "http://localhost:7364/api/amsp/v1",
+ agent: "demo/coder",
+ apiKey: keyField.value,
+});
+
+const answer = document.querySelector("#answer")!;
+for await (const event of client.run({ input: "What changed today?" })) {
+ if (event.type === "text.delta") answer.textContent += event.text;
+}
+```
+
+> [!WARNING]
+> 写在页面里的密钥,任何打开该页面的人都能读到。浏览器客户端只适合你和团队自用的工具,并在运行时输入密钥;否则就把密钥放在后端,由后端替页面调用 Agent。
+
+### 客户端参考
+
+```ts
+class AgentClient {
+ constructor(opts: {
+ baseUrl: string; // ".../api/amsp/v1"
+ agent: string; // "<projectId>/<agentId>"
+ apiKey?: string; // omitted = keyless; no environment variable is read
+ fetch?: typeof fetch; // the global fetch by default
+ headers?: Record<string, string>;
+ });
+ run(opts: RunOptions): Run;
+ ask(opts: RunOptions): Promise<RunResult>;
+ agent(): Promise<AgentInfo>;
+ session(sessionId: string): Promise<SessionInfo>;
+ abort(sessionId: string): Promise<boolean>;
+ approve(sessionId: string, toolCallId: string, decision: "allow" | "deny"): Promise<void>;
+}
+
+interface RunOptions {
+ input: string | InputItem[];
+ sessionId?: string;
+ signal?: AbortSignal;
+ onApproval?: (
+ request: ApprovalRequested,
+ ctx: { sessionId: string },
+ ) => "allow" | "deny" | Promise<"allow" | "deny">;
+}
+
+interface Run extends AsyncIterable<AmspEvent> {
+ readonly session: Promise<string>;
+ result(): Promise<RunResult>;
+ abort(): Promise<void>;
+}
+
+interface RunResult {
+ status: "completed" | "aborted" | "retryable" | "fatal";
+ error?: { code: string; message: string };
+ sessionId: string;
+ text: string;
+ items: AmspEvent[];
+ usage: TokenCounts;
+ sessionUsage: TokenCounts | null;
+ requests: number;
+}
+
+function parseArguments(call: { arguments: string }): Record<string, unknown> | null;
+function readSse(body: ReadableStream<Uint8Array>): AsyncGenerator<string>;
+class RunCollector {
+ add(event: AmspEvent): void;
+ readonly finished: boolean; // run.done has arrived
+ result(): RunResult; // throws AmspStreamError before run.done
+}
+class AmspHttpError extends Error { status: number; code: string }
+class AmspStreamError extends Error {}
+```
+
+`readSse` 是客户端自己的 SSE 读取器,导出给自行读取运行响应体的程序:它逐个产出每个事件的数据,`[DONE]` 也包括在内。`RunCollector` 把这样的程序解析出的事件归并为 `result()` 返回的那个 `RunResult`。
+
+## 命令行
+
+`penguin agent api` 在终端里管理 Agent 的 API,作用于正在运行的服务器,规则与 API 标签页相同:
+
+| 命令 | 作用 |
+| --- | --- |
+| `penguin agent api status --agent-id <id>` | 显示 API 是否开启、无密钥访问、审批模式、Base URL、Agent ID、密钥数量和管理员开关 |
+| `penguin agent api enable --agent-id <id> [--open \| --no-open] [--approve <mode>]` | 开启 API,可同时设置无密钥访问和审批模式 |
+| `penguin agent api disable --agent-id <id>` | 关闭 API |
+| `penguin agent api set --agent-id <id> [--open \| --no-open] [--approve <mode>]` | 修改无密钥访问或审批模式,不改变 API 的开关状态 |
+| `penguin agent api keys ls --agent-id <id>` | 列出密钥:id、名字、开头几个字符、创建时间、最近使用时间 |
+| `penguin agent api keys create --agent-id <id> --name <name>` | 签发密钥。stdout 上只有密钥本身,其余信息都写到 stderr,所以 `$(…)` 只会取到密钥 |
+| `penguin agent api keys rm <keyId> --agent-id <id>` | 删除密钥 |
+| `penguin agent api server on\|off` | 管理员开关 |
+
+每条命令都接受 `--project-id`、`--server` 和 `--json`。`--approve` 接受四种模式:`allow-all`、`read-only`、`always-ask`、`deny-all`。见 [CLI 参考](/cli)。
+
+会做出修改的命令(`enable`、`disable`、`set`、`keys create`、`keys rm` 和 `server`)需要你的登录:先运行一次 `penguin auth login`,或在服务器本机运行 `penguin auth token`。服务器拒绝携带本地 API token 的这些命令,CLI 随即带着这个登录再发一次。没有登录时,它们打印这条提示并以退出码 1 退出。`status` 和 `keys ls` 不需要登录。
+
+## 管理员开关
+
+**设置 › 服务器 › Agent API** 中有管理员的**允许 Agent API** 开关,缺省开启。关闭前会先确认;关闭后,所有 Agent API 请求(CORS 预检除外)都以 `403` `agent_api_disabled` 拒绝。各 Agent 的开关、审批模式和密钥都会保留,所有成员看到的 API 标签页开关都显示为不可用,并附有说明。见设置中的 [Agent API](/settings#agent-api)。这个设置是 `GET`/`PUT /api/admin/settings` 中的 `agentApiEnabled`,登录后在终端里用 `penguin agent api server on|off` 设置。
diff --git a/packages/docs/content/agents.en.md b/packages/docs/content/agents.en.md
index 3eea055d..47c2ae6f 100644
--- a/packages/docs/content/agents.en.md
+++ b/packages/docs/content/agents.en.md
@@ -1,6 +1,6 @@
---
title: Agents
-description: Create agents, and configure their prompts, tools, Skills, hooks, memory, vault and scheduled tasks.
+description: Create agents, and configure their prompts, tools, Skills, hooks, memory, vault, scheduled tasks and API.
---
An agent is a configured assistant in a Project. Each agent has its own instructions, runtime settings, tools, Skills, hook packages, memory, vault variables and scheduled tasks, stored together as its Agent State. You create agents and change their settings on the **Agents** page.
@@ -19,7 +19,7 @@ Every Project starts with the built-in agent `default_agent`. While it is the on
Each agent card shows:
-- the agent's name, its id, its Agent State version (for example `v3`) and its description;
+- the agent's name, its id, its Agent State version (for example `v3`) and its description; an agent whose API is on carries an API icon after its name (**API access on**);
- a row of counts: Sessions, tools, Skills, hook packages, memories, vault variables and scheduled tasks, plus when the agent was last modified. Select a count to open the matching settings tab;
- the agent's Session activity over the last 30 days;
- **New chat**, which starts a conversation with the agent; **Settings**, which opens its settings; an icon that opens its costs in **Cost Center**; and a delete button.
@@ -101,8 +101,9 @@ To open an agent's settings, select **Settings** on its card, select one of its
| **Memory** | The agent's memories and the memory prompts |
| **Vault** | Environment variables for the agent's commands |
| **Schedules** | Scheduled tasks |
+| **API** | Whether programs may call the agent over the Agent API, the approval mode of their conversations, and the keys |
-Each tab has its own address, `/agents/<agentId>?tab=<tab>`, where `<tab>` is `overview`, `prompt`, `runtime`, `tools`, `skills`, `hooks`, `memory`, `vault` or `schedules`.
+Each tab has its own address, `/agents/<agentId>?tab=<tab>`, where `<tab>` is `overview`, `prompt`, `runtime`, `tools`, `skills`, `hooks`, `memory`, `vault`, `schedules` or `api`.
### Save changes
@@ -122,7 +123,8 @@ Any Project member can change most settings. These actions are for the Project o
- turning **Enable hooks** on or off;
- editing vault variables, the **Enable vault** switch and the **Vault prompt**;
- creating, editing, enabling, disabling and deleting scheduled tasks, and editing the **Enable schedules** switch and the **Schedules prompt** (members can still use **Create with AI**);
-- importing memories.
+- importing memories;
+- everything on the **API** tab: the switch, the approval mode, keyless access and the keys.
## Overview tab
@@ -373,6 +375,10 @@ On each row, the owner can select **Disable** or **Enable**, **Edit**, or **Dele
- **Enable schedules** controls whether the scheduled tasks section enters the system prompt. With it off, tasks still run.
- **Schedules prompt** is the text that the `{{SCHEDULES}}` placeholder expands to. It teaches the model to manage scheduled tasks with its file tools, and its `{{SCHEDULE_LIST}}` placeholder lists the task names.
+## API tab
+
+The **API** tab lets programs outside PenguinHarness talk to the agent over HTTP: **Enable API access**, the **Approval mode for API conversations**, the **Base URL** and **Agent ID** under **Connection**, the **Keys**, **Allow keyless access**, **Examples** of a call, and, for the Project's owner, **Try it**, which runs the agent once through the API and shows the stream a program would receive. There is no **Save** button: the switches and the approval mode apply when you change them, and turning the API off or deleting a key asks first. To set it up and call the agent, see [Agent API](/agent-api).
+
## How it works
An agent's configuration and data live in its Agent State, the `agent_state/` folder that the Overview tab shows as **State path**. It holds `system_config.yaml`, `AGENTS.md`, the vault, tools, Skills, hook packages, scheduled tasks and memories. The agent's Traces are stored next to it, in the agent's own folder; see [Data layout](/sessions-and-traces#data-layout).
diff --git a/packages/docs/content/agents.zh.md b/packages/docs/content/agents.zh.md
index d3332a94..35b6f513 100644
--- a/packages/docs/content/agents.zh.md
+++ b/packages/docs/content/agents.zh.md
@@ -1,6 +1,6 @@
---
title: 智能体
-description: 创建 Agent,配置它的提示词、工具、Skill、钩子、记忆、密钥保险柜和定时任务。
+description: 创建 Agent,配置它的提示词、工具、Skill、钩子、记忆、密钥保险柜、定时任务和 API。
---
Agent 是 Project 里配置好的助手。每个 Agent 都有自己的指令、运行参数、工具、Skill、钩子包、记忆、密钥保险柜变量和定时任务,这些内容存放在一起,构成它的 Agent State。创建 Agent、修改设置,都在**智能体**页面上完成。
@@ -19,7 +19,7 @@ Agent 是 Project 里配置好的助手。每个 Agent 都有自己的指令、
每个 Agent 卡片显示:
-- Agent 的名称、id、Agent State 版本(例如 `v3`)和描述;
+- Agent 的名称、id、Agent State 版本(例如 `v3`)和描述;已开启 API 的 Agent 名称后带有 API 图标(**已开启 API 访问**);
- 一排数字:Session、工具、Skill、钩子包、记忆、密钥保险柜变量、定时任务的数量,以及最近一次修改的时间。点击任一数字即可打开对应的设置标签页;
- 这个 Agent 最近 30 天的 Session 活动;
- **新建对话**:和这个 Agent 开始对话;**设置**:打开它的设置;一个图标:在**成本中心**查看成本;以及一个删除按钮。
@@ -101,8 +101,9 @@ Agent 是 Project 里配置好的助手。每个 Agent 都有自己的指令、
| **记忆** | Agent 的记忆和记忆提示词 |
| **密钥保险柜** | Agent 命令用的环境变量 |
| **定时任务** | 定时任务 |
+| **API** | 是否允许程序经 Agent API 调用这个 Agent、这些对话的审批模式,以及密钥 |
-每个标签页都有自己的地址:`/agents/<agentId>?tab=<tab>`,其中 `<tab>` 是 `overview`、`prompt`、`runtime`、`tools`、`skills`、`hooks`、`memory`、`vault` 或 `schedules`。
+每个标签页都有自己的地址:`/agents/<agentId>?tab=<tab>`,其中 `<tab>` 是 `overview`、`prompt`、`runtime`、`tools`、`skills`、`hooks`、`memory`、`vault`、`schedules` 或 `api`。
### 保存修改
@@ -122,7 +123,8 @@ Agent 是 Project 里配置好的助手。每个 Agent 都有自己的指令、
- 打开或关闭**启用钩子**;
- 编辑密钥保险柜变量、**启用密钥保险柜**开关和**保险柜提示词**;
- 创建、编辑、启用、停用和删除定时任务,编辑**启用定时任务**开关和**定时任务提示词**(成员仍可使用**用 AI 创建**);
-- 导入记忆。
+- 导入记忆;
+- **API** 标签页上的一切:开关、审批模式、无密钥访问和密钥。
## 概览标签页
@@ -373,6 +375,10 @@ owner 可以在每一行选择**停用**或**启用**、**编辑**、**删除**
- **启用定时任务**控制定时任务区块是否进入系统提示词。关闭时,任务照常运行。
- **定时任务提示词**:`{{SCHEDULES}}` 占位符展开后的文本。它教模型用文件工具管理定时任务,其中的 `{{SCHEDULE_LIST}}` 占位符列出任务名。
+## API 标签页
+
+**API** 标签页让 PenguinHarness 之外的程序经 HTTP 与这个 Agent 对话:**开启 API 访问**、**API 会话的审批模式**、**连接**下的 **Base URL** 和 **Agent ID**、**密钥**、**允许无密钥访问**、调用**示例**,以及只对 Project 所有者显示的**试一试**:经 API 运行一次这个 Agent,按程序会收到的样子显示事件流。这个标签页没有**保存**按钮:开关和审批模式改动即生效,关闭 API 访问和删除密钥前会先确认。如何设置、如何调用,见 [Agent API](/agent-api)。
+
## 工作原理
Agent 的配置和数据存放在它的 Agent State 里,也就是概览标签页上 **State 路径**显示的 `agent_state/` 文件夹。里面有 `system_config.yaml`、`AGENTS.md`、密钥保险柜、工具、Skill、钩子包、定时任务和记忆。Agent 的 Trace 不在其中,而是存放在它旁边、这个 Agent 自己的文件夹里,见[数据目录](/sessions-and-traces#数据目录)。
diff --git a/packages/docs/content/amsp.en.md b/packages/docs/content/amsp.en.md
new file mode 100644
index 00000000..5a809778
--- /dev/null
+++ b/packages/docs/content/amsp.en.md
@@ -0,0 +1,233 @@
+---
+title: AMSP
+description: The Agent Message Stream Protocol — the event stream one run of an agent is served as through the Agent API, its grammar, every event, the errors and the versioning rule.
+---
+
+AMSP (Agent Message Stream Protocol) is the wire format of the [Agent API](/agent-api). Where [MMSP](https://www.npmjs.com/package/@prismshadow/mmsp) streams one model call, AMSP streams one run of an agent: one Task, with the model Requests it makes, the tools the agent runs and their results, approvals, compaction, errors and the final count of tokens, on a Session the caller continues by id. One run is one HTTP response.
+
+AMSP is a projection of the Session's live stream: the server translates the [OmniMessage](/omni-message) records and server events a run produces, and forwards both the fragments and the complete items as the engine produced them. OmniMessage gains no field for it. The types are in `@lmliheng/amsp` (`packages/amsp/src/types.ts`), which the server's translator and the client share.
+
+## Transport
+
+- The run is `POST <Base URL>/agents/:projectId/:agentId/runs` with `Content-Type: application/json`, `Accept: text/event-stream` and, unless the agent allows keyless access, `Authorization: Bearer <key>`. The body is described in [The run request](/agent-api#the-run-request).
+- The answer is `200` with `Content-Type: text/event-stream; charset=utf-8`, `Cache-Control: no-cache` and `X-Accel-Buffering: no`. Each event is one `data: <JSON>` block followed by a blank line; after the last event comes `data: [DONE]`. There are no `event:` or `id:` fields, so a dropped stream cannot be resumed.
+- After 15 seconds without an event, the server writes the comment `: keep-alive`, so proxies and clients see the connection is alive while the model or a tool is slow.
+- Every event carries `type` and `at` (ISO 8601, UTC). An event from a subagent's Session also carries `origin`, the chain of child Session ids from the outermost to the innermost, exactly as in OmniMessage; an event without `origin` belongs to the main Session.
+- Bytes travel as base64 text: `inline_data.done.data`, `inline_thinking.done.data`, a tool result's `images`, and `data:` URLs in the input.
+- A request refused before the stream gets an HTTP status and the error envelope; see [Errors](/agent-api#errors). Once the stream has started, an error is never a separate frame: `run.done` carries it.
+- Routing is case-sensitive.
+
+## Grammar
+
+```text
+stream := run.started body* run.done
+body := context.opened | mcp_connect.started | mcp_connect.done | tools.ready
+ | request | tool_result | approval | compaction | hook.fired
+ | text.done (role user) | image_url.done
+request := request.started (item | tool_result | approval | hook.fired)* request.done
+item := K.delta* K.done ; K = thinking | text | tool_call | inline_data | inline_thinking
+tool_result := tool_result.delta | tool_result.done ; one event each: a result is tool_result.delta* tool_result.done,
+ ; keyed by tool_call_id, and may straddle request.done
+approval := approval.requested | approval.decided
+compaction := compaction.started (summary.delta* | summary.done)? compaction.done
+```
+
+The rules a client can rely on:
+
+1. **Exactly one terminal.** `run.done` is the last event before `[DONE]`, whether the run completed, was aborted, failed, or the server failed while driving it (`status: "fatal"`, `error.code: "internal"`). A body that ends without it means the connection broke.
+2. **Items close with `.done`, and fragments are never reconciled with it.** A `.done` item carries the whole content. The server forwards the fragments and the complete item as the engine produced them and rebuilds neither from the other. For text and thinking the fragments, concatenated, equal the `.done`; for a tool call they need not: the fragments are the provider's text as it streamed, and `tool_call.done.arguments` is the engine's serialization of the parsed call, so `{"command": "ls"}` may stream and `{"command":"ls"}` arrive done — both parse to the same object. A `.done` may arrive with no fragments before it. A streamed compaction summary is the one item without a `.done` (rule 7).
+3. **One origin's model output is serial; tool results are not items.** Within one origin, the thinking, text, tool call and inline items come one after another: an item's `.done` precedes the next item's first fragment. Tool results, approvals and hook events may fall between any two events of an item, and the results of tools running in parallel interleave with each other; attribute them by `tool_call_id`. Different origins interleave freely; attribute by `origin`.
+4. **A Request pair encloses its model output, not its tools.** The engine runs a tool as soon as its call is complete, while the Request is still open: the approval is asked and answered before that Request's `request.done`, the result starts as soon as the call is approved, usually before `request.done`, and may end after it. Every result of a Request's calls arrives before the next `request.started` of the same origin. A retried attempt is a new pair: `request.done` with `status: "retryable"` and `retry_in_ms`, then `request.started` again.
+5. **Usage adds up.** `request.done.usage` is that attempt's count (`null` when there is none) and `compaction.done.usage` sums its attempts. `run.done.usage` is the sum of every `request.done.usage` and `compaction.done.usage` of the run; `run.done.session_usage` is the Session's running total as the engine last reported it, or `null`.
+6. **Unknown types are ignored.** A client must skip an event `type` it does not know.
+7. **Compaction holds only summaries.** Between `compaction.started` and `compaction.done` the only items are `summary.*`: the compaction's thinking is not forwarded, and `text.*` never appears. The engine streams a summary's fragments or delivers its text whole, never both, so a streamed summary is `summary.delta*` followed by `compaction.done` with no `summary.done`, and a whole one is a single `summary.done`. No `context.opened` follows a compaction: the context it opens is recorded in the Trace without being streamed. In practice `context.opened` marks a subagent's Session starting; the main Session streams one only on a model switch, which happens between runs.
+
+## Events
+
+Each event below also carries `at`, and `origin` when it comes from a subagent. Token counts are `{cache_read, cache_write, output, total}`; an error is `{code, message}`.
+
+### Run
+
+| Event | Fields | Meaning |
+| --- | --- | --- |
+| `run.started` | `session_id`, `agent` | First event: the Session the run is on (new or continued) and the agent, `<projectId>/<agentId>` |
+| `run.done` | `status`, `error?`, `requests`, `usage`, `session_usage` | Last event: how the run ended, how many model Requests it issued (retried attempts included), its token count and the Session's |
+
+`status` is `completed`, `aborted`, `retryable` or `fatal`, the same four values as OmniMessage's `stop_reason`. `error` is present when a Request or compaction failed for good, or the run was aborted.
+
+### Context and setup
+
+| Event | Fields | Meaning |
+| --- | --- | --- |
+| `context.opened` | `session_id`, `provider`, `model_id`, `context_window` | A new model context the engine streams: with `origin`, a subagent's Session starting; without, a model switch, which happens between runs. The context a compaction opens is not streamed |
+| `mcp_connect.started` | `servers` | The agent's MCP servers start connecting |
+| `mcp_connect.done` | `status`, `results`, `error?` | Each server's outcome: `{server, transport, status, duration_ms, tools?, error?}` |
+| `tools.ready` | `tools` | The tool definitions the model is given: `{name, description, parameters?}` |
+
+### Requests
+
+| Event | Fields | Meaning |
+| --- | --- | --- |
+| `request.started` | `request` | A model Request begins; `request` counts from 1 within the run (a subagent counts its own) |
+| `request.done` | `request`, `status`, `usage`, `error?`, `attempt?`, `retry_in_ms?` | It ended. `retry_in_ms` is present only when the engine will retry within the run |
+
+### Items
+
+| Event | Fields | Meaning |
+| --- | --- | --- |
+| `text.delta` | `role: "assistant"`, `text` | A fragment of the model's text; may be empty |
+| `text.done` | `role`, `text`, `stop_reason`, `sender?` | A complete text. `role: "user"` is a message added during the run, such as steering or a hook's continuation, with `sender` saying who added it |
+| `thinking.delta` / `thinking.done` | `thinking`, `stop_reason` on done | The model's thinking |
+| `tool_call.delta` | `tool_call_id`, `name`, `arguments` | A fragment of a tool call: `name` is set on the first one, `arguments` is a piece of the text the provider streamed |
+| `tool_call.done` | `tool_call_id`, `name`, `arguments`, `stop_reason` | The complete call; `arguments` is the engine's serialization of the parsed call as a JSON string |
+| `tool_result.delta` | `tool_call_id`, `output`, `images?` | Output a running tool has produced so far, possibly before the Request's `request.done`; `images` arrive whole, in one fragment |
+| `tool_result.done` | `tool_call_id`, `output`, `images?`, `stop_reason` | The tool's result as the model receives it; may follow the Request's `request.done`, always before the next `request.started` |
+| `inline_data.done` | `role`, `mime_type`, `data`, `stop_reason` | An image or other data inline in the conversation, base64 |
+| `inline_thinking.done` | `mime_type`, `data`, `stop_reason` | Opaque thinking data a provider returns, base64 |
+| `image_url.done` | `role: "user"`, `image_url` | An image added to the conversation during the run |
+| `summary.delta` / `summary.done` | `text`, `stop_reason` on done | The summary a compaction writes: streamed as fragments with no `.done`, or delivered whole as one `summary.done` |
+
+`arguments` stays a string, unlike MMSP, which parses it. The fragments carry the provider's text as it streamed; `tool_call.done.arguments` is the engine's own serialization of the parsed call, also what the Trace keeps, so the two need not match character for character but parse to the same object. A call cut short (`stop_reason` other than `completed`) carries the text received so far. The client's `parseArguments` turns either into an object.
+
+The run's own input is not repeated on the stream; `run.started` follows the request.
+
+### Approvals
+
+| Event | Fields | Meaning |
+| --- | --- | --- |
+| `approval.requested` | `tool_call: {tool_call_id, name, arguments}` | A tool call waits for an answer: `POST /sessions/:sessionId/approvals/:toolCallId` with `{"decision": "allow" \| "deny"}` |
+| `approval.decided` | `tool_call_id`, `decision` | The decision on a tool call, for every call the model makes: by the approval mode, a hook, the caller or the Web App. `decision` is `allow`, `deny`, or `forbidden` when the command policy vetoed the call |
+
+Only a call that waits is sent as `approval.requested`; one the approval mode settles goes straight to `approval.decided`. Answer a subagent's approval through the main Session's id, the one `run.started` named.
+
+### Compaction and hooks
+
+| Event | Fields | Meaning |
+| --- | --- | --- |
+| `compaction.started` | `reason`, `mode`, `context`, `turns` | Context compaction begins: `reason` is `context`, `turns` or `manual`, `mode` is `summarize` or `discard` |
+| `compaction.done` | `reason`, `mode`, `status`, `usage`, `error?`, `attempt?` | It ended |
+| `hook.fired` | `hook`, `name`, `decision?`, `reason?`, `output?` | A hook ran at `stop`, `pre_tool_use` or `user_prompt`, and what it decided |
+
+## Examples
+
+A plain answer:
+
+```text
+data: {"type":"run.started","at":"2026-10-07T10:00:00.000Z","session_id":"session-2026-10-07-10-00-00-3f9a1c2e","agent":"demo/coder"}
+data: {"type":"request.started","at":"…","request":1}
+data: {"type":"text.delta","at":"…","role":"assistant","text":""}
+data: {"type":"text.delta","at":"…","role":"assistant","text":"Hello"}
+data: {"type":"text.delta","at":"…","role":"assistant","text":"!"}
+data: {"type":"text.done","at":"…","role":"assistant","text":"Hello!","stop_reason":"completed"}
+data: {"type":"request.done","at":"…","request":1,"status":"completed","usage":{"cache_read":0,"cache_write":0,"output":2,"total":412}}
+data: {"type":"run.done","at":"…","status":"completed","requests":1,"usage":{"cache_read":0,"cache_write":0,"output":2,"total":412},"session_usage":{"cache_read":0,"cache_write":0,"output":2,"total":412}}
+data: [DONE]
+```
+
+Each event is followed by a blank line on the wire; the examples leave them out.
+
+A tool call that waits for the caller's approval, then a second Request. The tool runs while the first Request is still open: the approval and the start of the result come before its `request.done`, the rest of the result after it. The streamed arguments are the provider's text; the `.done` carries the engine's serialization of the parsed call:
+
+```text
+data: {"type":"run.started",…}
+data: {"type":"request.started","request":1,…}
+data: {"type":"tool_call.delta","tool_call_id":"call_1","name":"exec_command","arguments":"",…}
+data: {"type":"tool_call.delta","tool_call_id":"call_1","name":"","arguments":"{\"command\": \"ls\"}",…}
+data: {"type":"tool_call.done","tool_call_id":"call_1","name":"exec_command","arguments":"{\"command\":\"ls\"}","stop_reason":"completed",…}
+data: {"type":"approval.requested","tool_call":{"tool_call_id":"call_1","name":"exec_command","arguments":"{\"command\":\"ls\"}"},…}
+ ← caller: POST /api/amsp/v1/sessions/<id>/approvals/call_1 {"decision":"allow"} → 204
+data: {"type":"approval.decided","tool_call_id":"call_1","decision":"allow",…}
+data: {"type":"tool_result.delta","tool_call_id":"call_1","output":"",…}
+data: {"type":"request.done","request":1,"status":"completed","usage":{…},…}
+data: {"type":"tool_result.delta","tool_call_id":"call_1","output":"README.md\nsrc\n",…}
+data: {"type":"tool_result.done","tool_call_id":"call_1","output":"README.md\nsrc\n","stop_reason":"completed",…}
+data: {"type":"request.started","request":2,…}
+data: {"type":"text.delta",…} … data: {"type":"text.done","text":"Two entries: README.md and src.",…}
+data: {"type":"request.done","request":2,"status":"completed","usage":{…},…}
+data: {"type":"run.done","status":"completed","requests":2,"usage":{…},"session_usage":{…},…}
+data: [DONE]
+```
+
+A compaction between two Requests. Its summary is streamed, so it has no `summary.done`, and no `context.opened` follows:
+
+```text
+data: {"type":"request.done","request":1,"status":"completed","usage":{…},…}
+data: {"type":"compaction.started","reason":"context","mode":"summarize","context":300,"turns":1,…}
+data: {"type":"summary.delta","text":"",…}
+data: {"type":"summary.delta","text":"Summary.",…}
+data: {"type":"compaction.done","reason":"context","mode":"summarize","status":"completed","usage":{…},"attempt":1,…}
+data: {"type":"request.started","request":2,…}
+```
+
+A transient failure and its retry, then the caller aborts:
+
+```text
+data: {"type":"run.started",…}
+data: {"type":"request.started","request":1,…}
+data: {"type":"request.done","request":1,"status":"retryable","usage":null,"error":{"code":"network","message":"fetch failed"},"attempt":1,"retry_in_ms":1000,…}
+: keep-alive
+data: {"type":"request.started","request":2,…}
+data: {"type":"text.delta","text":"Let me",…}
+ ← caller: POST /api/amsp/v1/sessions/<id>/abort → 202
+data: {"type":"text.done","text":"Let me","stop_reason":"aborted",…}
+data: {"type":"request.done","request":2,"status":"aborted","usage":null,"attempt":2,…}
+data: {"type":"run.done","status":"aborted","error":{"code":"user_abort","message":"…"},"requests":2,"usage":{…},"session_usage":null,…}
+data: [DONE]
+```
+
+## Errors in the stream
+
+`run.done.status` says how the run ended: `aborted` when it was aborted; otherwise the status of the Request or compaction that failed for good, with its error; `fatal` without an error when the run reached the agent's turn limit; `completed` otherwise. `run.done.error.code` takes the same codes OmniMessage records, plus two of AMSP's own:
+
+| `code` | Meaning |
+| --- | --- |
+| `user_abort` | The run was aborted: by `POST …/abort`, the caller disconnecting, or someone in the Web App |
+| `backoff_interrupted`, `compaction_interrupted` | An abort arrived while the engine waited to retry, or during a compaction |
+| `timeout` | The model's connection went silent |
+| `network` | A dropped connection, a provider `429` or `5xx`, or a failure that fits nowhere else |
+| `malformed` | The model's response failed to parse or was cut short |
+| `auth` | The provider refused the credentials |
+| `rejected` | The provider refused the request for good (parameters, quota) |
+| `unsupported` | The request asked for something the model cannot do |
+| `invalid_input` | The input could not be assembled into a request |
+| `connect_failed` | An MCP server failed to connect (on `mcp_connect.done`) |
+| `internal` | The server failed while driving the run |
+| `session_rebuilt` | The server had to rebuild the Session under a new id and could not follow it; the message names the new id |
+
+A run that ends `fatal` or `retryable` is still answered `200`: the HTTP status only covers the request itself.
+
+## From OmniMessage to AMSP
+
+The server's translator reads what the Session publishes while it runs and writes AMSP events:
+
+| OmniMessage record or server event | AMSP |
+| --- | --- |
+| Anything the Session published before the run's input (an idle `task_state` a subagent's state change re-published, a background subagent's output) | Not sent: the translator starts at the input's echo |
+| The run's own input | Not sent |
+| `session_meta` | `context.opened`: a subagent's, or a model switch's between runs; the context a compaction opens is written to the Trace only |
+| `mcp_connect_begin` / `mcp_connect_end` | `mcp_connect.started` / `mcp_connect.done` |
+| `tool_list_ready` | `tools.ready` |
+| `request_begin` / `request_end` | `request.started` / `request.done` |
+| `token_usage` | Not sent: its counts go on the next `request.done` (or `compaction.done`), and its Session total on `run.done` |
+| `partial_text`, `partial_thinking`, `partial_tool_call`, `partial_tool_call_output`, at `start` and `delta` | `text.delta`, `thinking.delta`, `tool_call.delta`, `tool_result.delta`; inside a compaction, text is `summary.delta` (no `summary.done` follows it) and thinking is not sent |
+| A `partial_*` at `stop` | Not sent |
+| `text`, `thinking`, `tool_call`, `tool_call_output` | `text.done`, `thinking.done`, `tool_call.done`, `tool_result.done`; inside a compaction, a text the engine delivered whole is `summary.done` and thinking is not sent |
+| `inline_data`, `inline_thinking`, `image_url` | `inline_data.done`, `inline_thinking.done`, `image_url.done` |
+| The `approval_request` server event / `approval_decision` | `approval.requested` / `approval.decided` |
+| `compaction_begin` / `compaction_end` | `compaction.started` / `compaction.done` |
+| `hook` | `hook.fired` |
+| `abort` | Not sent: it makes `run.done` `aborted` with its error |
+| The `task_state` server event turning `idle` | `run.done` |
+
+Fields that serve only the Trace, such as provider `fidelity` and `session_meta.source`, are not carried: an API run's Session is an API Session by construction.
+
+## Versioning
+
+- The version is in the path, `/api/amsp/v1`; events carry none.
+- Within `/v1`, changes only add: new event types and new optional fields. A client that ignores what it does not know keeps working.
+- A change to what an existing field means is a new version, `/v2`, served beside `/v1`.
+- Event names are `<subject>.<phase>`; items are `K.delta` and `K.done`, as in MMSP. A "run" on the wire is one Task in PenguinHarness's terms.
+
+## Reading the stream yourself
+
+Any SSE reader works, as long as it can send `Authorization` and a POST body: use `fetch`, not `EventSource`. Read it the way an `EventSource` would: lines end in LF, CRLF or a lone CR; a blank line ends an event; lines starting with `:` are comments; the `data:` lines of one event join with a newline; stop at `data: [DONE]`. `readSse` from `@lmliheng/amsp` does exactly this for a `fetch` body and yields each event's data.
diff --git a/packages/docs/content/amsp.zh.md b/packages/docs/content/amsp.zh.md
new file mode 100644
index 00000000..2bffa312
--- /dev/null
+++ b/packages/docs/content/amsp.zh.md
@@ -0,0 +1,233 @@
+---
+title: AMSP
+description: Agent Message Stream Protocol:经 Agent API 返回 Agent 一次运行所用的事件流,包括语法、全部事件、错误与版本规则。
+---
+
+AMSP(Agent Message Stream Protocol)是 [Agent API](/agent-api) 的传输格式。[MMSP](https://www.npmjs.com/package/@prismshadow/mmsp) 流式传输一次模型调用,AMSP 流式传输 Agent 的一次运行:一个 Task,包括它发出的模型 Request、Agent 执行的工具及其结果、审批、上下文压缩、错误和最终的 Token 计数;运行发生在一个 Session 上,调用方凭 id 延续它。一次运行就是一个 HTTP 响应。
+
+AMSP 是 Session 实时流的投影:服务器把一次运行产生的 [OmniMessage](/omni-message) 记录和服务器事件翻译过来,分片和完整内容项都按引擎产出的原样转发。OmniMessage 没有为它增加任何字段。类型定义在 `@lmliheng/amsp`(`packages/amsp/src/types.ts`)中,服务器的翻译器和客户端共用这份定义。
+
+## 传输
+
+- 运行请求是 `POST <Base URL>/agents/:projectId/:agentId/runs`,带 `Content-Type: application/json`、`Accept: text/event-stream`,以及 `Authorization: Bearer <key>`(除非该 Agent 允许无密钥访问)。请求体见[运行请求](/agent-api#运行请求)。
+- 响应是 `200`,带 `Content-Type: text/event-stream; charset=utf-8`、`Cache-Control: no-cache` 和 `X-Accel-Buffering: no`。每个事件是一个 `data: <JSON>` 块,后跟一个空行;最后一个事件之后是 `data: [DONE]`。没有 `event:` 或 `id:` 字段,所以中断的流无法续传。
+- 连续 15 秒没有事件时,服务器写入注释 `: keep-alive`,让代理和客户端知道连接在模型或工具较慢时依然存活。
+- 每个事件都带 `type` 和 `at`(ISO 8601,UTC)。来自子 Agent Session 的事件还带 `origin`,即由外到内的子 Session id 链,与 OmniMessage 完全相同;不带 `origin` 的事件属于主 Session。
+- 字节以 base64 文本传送:`inline_data.done.data`、`inline_thinking.done.data`、工具结果的 `images`,以及输入中的 `data:` URL。
+- 在事件流开始之前被拒绝的请求,得到 HTTP 状态码和错误信封,见[错误](/agent-api#错误)。事件流一旦开始,错误就不会以单独的帧出现,而是由 `run.done` 携带。
+- 路由区分大小写。
+
+## 语法
+
+```text
+stream := run.started body* run.done
+body := context.opened | mcp_connect.started | mcp_connect.done | tools.ready
+ | request | tool_result | approval | compaction | hook.fired
+ | text.done (role user) | image_url.done
+request := request.started (item | tool_result | approval | hook.fired)* request.done
+item := K.delta* K.done ; K = thinking | text | tool_call | inline_data | inline_thinking
+tool_result := tool_result.delta | tool_result.done ; 各为单个事件:一次结果为 tool_result.delta* tool_result.done,
+ ; 按 tool_call_id 归属,可以跨过 request.done
+approval := approval.requested | approval.decided
+compaction := compaction.started (summary.delta* | summary.done)? compaction.done
+```
+
+客户端可以依赖的规则:
+
+1. **有且只有一个终止事件。** `run.done` 是 `[DONE]` 之前的最后一个事件,无论运行是完成、被中止、失败,还是服务器在驱动运行时出错(`status: "fatal"`、`error.code: "internal"`)。响应体在它之前结束,意味着连接断了。
+2. **内容项以 `.done` 收尾,分片与它从不对账。** `.done` 携带完整内容。服务器把分片和完整内容项都按引擎产出的原样转发,不由一方重建另一方。文本和思考的分片拼接起来与 `.done` 相同;工具调用则未必:分片是供应商流式输出的原文,`tool_call.done.arguments` 是引擎对解析后参数的再序列化,所以流里可能是 `{"command": "ls"}`,`.done` 里是 `{"command":"ls"}`,两者解析为同一个对象。`.done` 之前也可能没有任何分片。流式产出的压缩摘要是唯一没有 `.done` 的内容项(规则 7)。
+3. **同一来源的模型输出依次出现,工具结果不是内容项。** 在同一 `origin` 内,思考、文本、工具调用和内联内容项依次出现:一项的 `.done` 先于下一项的第一个分片。工具结果、审批和钩子事件可以落在一项的任意两个事件之间;工具并行执行时,结果之间彼此交错,按 `tool_call_id` 归属。不同来源之间可以任意交错,按 `origin` 归属。
+4. **Request 成对包住的是其模型输出,不是其工具执行。** 引擎在调用完整时就开始执行工具,此时 Request 尚未结束:审批的请求和决定都在该 Request 的 `request.done` 之前;结果在调用获准后即开始,通常也在 `request.done` 之前,并可能在它之后才结束。一次 Request 的全部结果都在同一来源的下一个 `request.started` 之前到齐。重试的尝试是新的一对:先是 `status: "retryable"` 且带 `retry_in_ms` 的 `request.done`,再是新的 `request.started`。
+5. **用量可以加总。** `request.done.usage` 是该次尝试的计数(没有时为 `null`),`compaction.done.usage` 是其各次尝试之和。`run.done.usage` 是本次运行全部 `request.done.usage` 与 `compaction.done.usage` 之和;`run.done.session_usage` 是引擎最后报告的 Session 累计值,没有时为 `null`。
+6. **忽略未知类型。** 客户端必须跳过不认识的事件 `type`。
+7. **压缩期间只有摘要。** 在 `compaction.started` 与 `compaction.done` 之间,内容项只会是 `summary.*`:压缩请求的思考不转发,`text.*` 也不会出现。引擎对摘要只流式产出分片或只给出完整文本,两者不会都有:流式产出的摘要是 `summary.delta*` 直接接 `compaction.done`,没有 `summary.done`;整段给出的摘要是一个 `summary.done`。压缩之后没有 `context.opened`:压缩开出的新上下文写进 Trace,不进流。实际上 `context.opened` 标记的是子 Agent 的 Session 开始;主 Session 只在切换模型时流出它,而切换发生在两次运行之间。
+
+## 事件
+
+下面每个事件还都带 `at`,来自子 Agent 时还带 `origin`。Token 计数为 `{cache_read, cache_write, output, total}`;错误为 `{code, message}`。
+
+### 运行
+
+| 事件 | 字段 | 含义 |
+| --- | --- | --- |
+| `run.started` | `session_id`、`agent` | 第一个事件:运行所在的 Session(新建的或延续的)和 Agent,形如 `<projectId>/<agentId>` |
+| `run.done` | `status`、`error?`、`requests`、`usage`、`session_usage` | 最后一个事件:运行如何结束、发出了多少次模型 Request(含重试的尝试)、本次运行的 Token 计数和 Session 的累计值 |
+
+`status` 取 `completed`、`aborted`、`retryable` 或 `fatal`,与 OmniMessage 的 `stop_reason` 是同一组取值。某次 Request 或压缩最终失败、或运行被中止时,带有 `error`。
+
+### 上下文与准备
+
+| 事件 | 字段 | 含义 |
+| --- | --- | --- |
+| `context.opened` | `session_id`、`provider`、`model_id`、`context_window` | 引擎流出的新模型上下文:带 `origin` 时,表示一个子 Agent 的 Session 开始了;不带时是切换模型,它发生在两次运行之间。压缩开出的上下文不进流 |
+| `mcp_connect.started` | `servers` | Agent 的 MCP Server 开始连接 |
+| `mcp_connect.done` | `status`、`results`、`error?` | 每个 Server 的结果:`{server, transport, status, duration_ms, tools?, error?}` |
+| `tools.ready` | `tools` | 提供给模型的工具定义:`{name, description, parameters?}` |
+
+### 请求
+
+| 事件 | 字段 | 含义 |
+| --- | --- | --- |
+| `request.started` | `request` | 一次模型 Request 开始;`request` 在本次运行内从 1 计数(子 Agent 各自计数) |
+| `request.done` | `request`、`status`、`usage`、`error?`、`attempt?`、`retry_in_ms?` | 它结束了。只有引擎会在本次运行内重试时才带 `retry_in_ms` |
+
+### 内容项
+
+| 事件 | 字段 | 含义 |
+| --- | --- | --- |
+| `text.delta` | `role: "assistant"`、`text` | 模型文本的一个分片,可以为空 |
+| `text.done` | `role`、`text`、`stop_reason`、`sender?` | 一段完整文本。`role: "user"` 表示运行途中加入的消息,例如引导消息或钩子的续写,由 `sender` 说明是谁加入的 |
+| `thinking.delta` / `thinking.done` | `thinking`,done 另带 `stop_reason` | 模型的思考 |
+| `tool_call.delta` | `tool_call_id`、`name`、`arguments` | 工具调用的一个分片:第一个分片带 `name`,`arguments` 是供应商流式输出原文的一段 |
+| `tool_call.done` | `tool_call_id`、`name`、`arguments`、`stop_reason` | 完整的调用;`arguments` 是引擎对解析后参数的再序列化,为 JSON 字符串 |
+| `tool_result.delta` | `tool_call_id`、`output`、`images?` | 运行中的工具到目前为止的输出,可能出现在该 Request 的 `request.done` 之前;`images` 整组出现在一个分片里 |
+| `tool_result.done` | `tool_call_id`、`output`、`images?`、`stop_reason` | 模型收到的工具结果;可能在该 Request 的 `request.done` 之后,但总在下一个 `request.started` 之前 |
+| `inline_data.done` | `role`、`mime_type`、`data`、`stop_reason` | 对话中内联的图片或其他数据,base64 |
+| `inline_thinking.done` | `mime_type`、`data`、`stop_reason` | 供应商返回的不透明思考数据,base64 |
+| `image_url.done` | `role: "user"`、`image_url` | 运行途中加入对话的图片 |
+| `summary.delta` / `summary.done` | `text`,done 另带 `stop_reason` | 压缩写出的摘要:流式产出时只有分片、没有 `.done`,整段给出时是一个 `summary.done` |
+
+与 MMSP 解析后的对象不同,`arguments` 保持为字符串。分片携带供应商流式输出的原文;`tool_call.done.arguments` 是引擎对解析后参数的再序列化,也是 Trace 保存的内容,所以两者不必逐字相同,但解析为同一个对象。被打断的调用(`stop_reason` 不是 `completed`)携带的是已收到的原文。客户端的 `parseArguments` 把任一种转成对象。
+
+运行自身的输入不会在流中重复出现;请求之后紧接着就是 `run.started`。
+
+### 审批
+
+| 事件 | 字段 | 含义 |
+| --- | --- | --- |
+| `approval.requested` | `tool_call: {tool_call_id, name, arguments}` | 一次工具调用在等待回答:以 `{"decision": "allow" \| "deny"}` 调用 `POST /sessions/:sessionId/approvals/:toolCallId` |
+| `approval.decided` | `tool_call_id`、`decision` | 对一次工具调用的决定,模型的每次调用都有:由审批模式、钩子、调用方或 Web App 做出。`decision` 为 `allow`、`deny`,命令策略否决时为 `forbidden` |
+
+只有等待中的调用才会以 `approval.requested` 发出;审批模式直接决定的调用只有 `approval.decided`。子 Agent 的审批也通过主 Session 的 id(即 `run.started` 给出的那个)回答。
+
+### 压缩与钩子
+
+| 事件 | 字段 | 含义 |
+| --- | --- | --- |
+| `compaction.started` | `reason`、`mode`、`context`、`turns` | 上下文压缩开始:`reason` 为 `context`、`turns` 或 `manual`,`mode` 为 `summarize` 或 `discard` |
+| `compaction.done` | `reason`、`mode`、`status`、`usage`、`error?`、`attempt?` | 压缩结束 |
+| `hook.fired` | `hook`、`name`、`decision?`、`reason?`、`output?` | 某个钩子在 `stop`、`pre_tool_use` 或 `user_prompt` 处运行,以及它的决定 |
+
+## 示例
+
+一次直接回答:
+
+```text
+data: {"type":"run.started","at":"2026-10-07T10:00:00.000Z","session_id":"session-2026-10-07-10-00-00-3f9a1c2e","agent":"demo/coder"}
+data: {"type":"request.started","at":"…","request":1}
+data: {"type":"text.delta","at":"…","role":"assistant","text":""}
+data: {"type":"text.delta","at":"…","role":"assistant","text":"Hello"}
+data: {"type":"text.delta","at":"…","role":"assistant","text":"!"}
+data: {"type":"text.done","at":"…","role":"assistant","text":"Hello!","stop_reason":"completed"}
+data: {"type":"request.done","at":"…","request":1,"status":"completed","usage":{"cache_read":0,"cache_write":0,"output":2,"total":412}}
+data: {"type":"run.done","at":"…","status":"completed","requests":1,"usage":{"cache_read":0,"cache_write":0,"output":2,"total":412},"session_usage":{"cache_read":0,"cache_write":0,"output":2,"total":412}}
+data: [DONE]
+```
+
+在实际传输中每个事件后面都跟一个空行,示例里省略了。
+
+一次需要调用方审批的工具调用,之后是第二次 Request。工具在第一次 Request 尚未结束时执行:审批和结果的开头在它的 `request.done` 之前,结果的其余部分在其后。分片里的参数是供应商的原文,`.done` 里的是引擎对解析后参数的再序列化:
+
+```text
+data: {"type":"run.started",…}
+data: {"type":"request.started","request":1,…}
+data: {"type":"tool_call.delta","tool_call_id":"call_1","name":"exec_command","arguments":"",…}
+data: {"type":"tool_call.delta","tool_call_id":"call_1","name":"","arguments":"{\"command\": \"ls\"}",…}
+data: {"type":"tool_call.done","tool_call_id":"call_1","name":"exec_command","arguments":"{\"command\":\"ls\"}","stop_reason":"completed",…}
+data: {"type":"approval.requested","tool_call":{"tool_call_id":"call_1","name":"exec_command","arguments":"{\"command\":\"ls\"}"},…}
+ ← caller: POST /api/amsp/v1/sessions/<id>/approvals/call_1 {"decision":"allow"} → 204
+data: {"type":"approval.decided","tool_call_id":"call_1","decision":"allow",…}
+data: {"type":"tool_result.delta","tool_call_id":"call_1","output":"",…}
+data: {"type":"request.done","request":1,"status":"completed","usage":{…},…}
+data: {"type":"tool_result.delta","tool_call_id":"call_1","output":"README.md\nsrc\n",…}
+data: {"type":"tool_result.done","tool_call_id":"call_1","output":"README.md\nsrc\n","stop_reason":"completed",…}
+data: {"type":"request.started","request":2,…}
+data: {"type":"text.delta",…} … data: {"type":"text.done","text":"Two entries: README.md and src.",…}
+data: {"type":"request.done","request":2,"status":"completed","usage":{…},…}
+data: {"type":"run.done","status":"completed","requests":2,"usage":{…},"session_usage":{…},…}
+data: [DONE]
+```
+
+两次 Request 之间的一次压缩。摘要是流式产出的,所以没有 `summary.done`,之后也没有 `context.opened`:
+
+```text
+data: {"type":"request.done","request":1,"status":"completed","usage":{…},…}
+data: {"type":"compaction.started","reason":"context","mode":"summarize","context":300,"turns":1,…}
+data: {"type":"summary.delta","text":"",…}
+data: {"type":"summary.delta","text":"Summary.",…}
+data: {"type":"compaction.done","reason":"context","mode":"summarize","status":"completed","usage":{…},"attempt":1,…}
+data: {"type":"request.started","request":2,…}
+```
+
+一次临时故障及其重试,之后调用方中止了运行:
+
+```text
+data: {"type":"run.started",…}
+data: {"type":"request.started","request":1,…}
+data: {"type":"request.done","request":1,"status":"retryable","usage":null,"error":{"code":"network","message":"fetch failed"},"attempt":1,"retry_in_ms":1000,…}
+: keep-alive
+data: {"type":"request.started","request":2,…}
+data: {"type":"text.delta","text":"Let me",…}
+ ← caller: POST /api/amsp/v1/sessions/<id>/abort → 202
+data: {"type":"text.done","text":"Let me","stop_reason":"aborted",…}
+data: {"type":"request.done","request":2,"status":"aborted","usage":null,"attempt":2,…}
+data: {"type":"run.done","status":"aborted","error":{"code":"user_abort","message":"…"},"requests":2,"usage":{…},"session_usage":null,…}
+data: [DONE]
+```
+
+## 流中的错误
+
+`run.done.status` 说明运行如何结束:被中止时为 `aborted`;否则为最终失败的那次 Request 或压缩的状态,并带其错误;运行达到 Agent 的轮次上限时为不带错误的 `fatal`;其余情况为 `completed`。`run.done.error.code` 取 OmniMessage 记录的同一组错误码,另加 AMSP 自己的两个:
+
+| `code` | 含义 |
+| --- | --- |
+| `user_abort` | 运行被中止:经 `POST …/abort`、调用方断开连接,或有人在 Web App 中中止 |
+| `backoff_interrupted`、`compaction_interrupted` | 中止发生在引擎等待重试期间,或压缩期间 |
+| `timeout` | 模型连接没有了动静 |
+| `network` | 连接中断、供应商返回 `429` 或 `5xx`,或无法归类的故障 |
+| `malformed` | 模型响应解析失败或被截断 |
+| `auth` | 供应商拒绝了凭据 |
+| `rejected` | 供应商明确拒绝了请求(参数、配额) |
+| `unsupported` | 请求要求了模型做不到的事 |
+| `invalid_input` | 输入无法组装成请求 |
+| `connect_failed` | 某个 MCP Server 连接失败(出现在 `mcp_connect.done` 上) |
+| `internal` | 服务器在驱动运行时出错 |
+| `session_rebuilt` | 服务器不得不以新 id 重建 Session,又无法跟随过去;message 中给出新 id |
+
+以 `fatal` 或 `retryable` 结束的运行,HTTP 响应仍是 `200`:HTTP 状态码只反映请求本身。
+
+## 从 OmniMessage 到 AMSP
+
+服务器的翻译器读取 Session 运行时发布的内容,写出 AMSP 事件:
+
+| OmniMessage 记录或服务器事件 | AMSP |
+| --- | --- |
+| Session 在本次运行的输入之前发布的一切(子 Agent 状态变化重发的空闲 `task_state`、后台子 Agent 的输出) | 不发送:翻译器从输入的回显开始 |
+| 运行自身的输入 | 不发送 |
+| `session_meta` | `context.opened`:子 Agent 的,或两次运行之间切换模型的;压缩开出的上下文只写 Trace |
+| `mcp_connect_begin` / `mcp_connect_end` | `mcp_connect.started` / `mcp_connect.done` |
+| `tool_list_ready` | `tools.ready` |
+| `request_begin` / `request_end` | `request.started` / `request.done` |
+| `token_usage` | 不发送:其计数写到下一个 `request.done`(或 `compaction.done`)上,Session 累计值写到 `run.done` 上 |
+| `partial_text`、`partial_thinking`、`partial_tool_call`、`partial_tool_call_output` 的 `start` 与 `delta` | `text.delta`、`thinking.delta`、`tool_call.delta`、`tool_result.delta`;压缩期间的文本为 `summary.delta`(其后没有 `summary.done`),压缩期间的思考不发送 |
+| `partial_*` 的 `stop` | 不发送 |
+| `text`、`thinking`、`tool_call`、`tool_call_output` | `text.done`、`thinking.done`、`tool_call.done`、`tool_result.done`;压缩期间引擎整段给出的文本为 `summary.done`,压缩期间的思考不发送 |
+| `inline_data`、`inline_thinking`、`image_url` | `inline_data.done`、`inline_thinking.done`、`image_url.done` |
+| 服务器事件 `approval_request` / `approval_decision` | `approval.requested` / `approval.decided` |
+| `compaction_begin` / `compaction_end` | `compaction.started` / `compaction.done` |
+| `hook` | `hook.fired` |
+| `abort` | 不发送:它使 `run.done` 成为带该错误的 `aborted` |
+| 服务器事件 `task_state` 变为 `idle` | `run.done` |
+
+只为 Trace 服务的字段不会传送,例如供应商的 `fidelity` 和 `session_meta.source`:API 运行所在的 Session 本来就是 API 会话。
+
+## 版本
+
+- 版本写在路径里:`/api/amsp/v1`;事件本身不带版本。
+- 在 `/v1` 之内只做增加:新的事件类型和新的可选字段。忽略未知内容的客户端可以继续工作。
+- 改变已有字段含义的变更属于新版本 `/v2`,与 `/v1` 并存。
+- 事件名形如 `<subject>.<phase>`;内容项为 `K.delta` 与 `K.done`,与 MMSP 一致。传输中的一次 run 即 PenguinHarness 术语中的一个 Task。
+
+## 自行读取流
+
+任何能发送 `Authorization` 和 POST 请求体的 SSE 读取方式都可以:请用 `fetch`,不要用 `EventSource`。按 `EventSource` 的规则读取:行以 LF、CRLF 或单独的 CR 结束;空行结束一个事件;以 `:` 开头的行是注释;同一事件的多行 `data:` 以换行符连接;读到 `data: [DONE]` 时停止。`@lmliheng/amsp` 中的 `readSse` 正是这样读取 `fetch` 的响应体,并逐个产出每个事件的数据。
diff --git a/packages/docs/content/architecture.en.md b/packages/docs/content/architecture.en.md
index 4c3e9c41..c7bb7873 100644
--- a/packages/docs/content/architecture.en.md
+++ b/packages/docs/content/architecture.en.md
@@ -36,6 +36,7 @@ The CLI and the Web App talk to the Server over HTTP and SSE. Among the shipped
| --- | --- |
| `packages/core` | SDK and engine: `context_engine`, OmniMessage, the LLM and Environment interfaces, hooks, state and Trace |
| `packages/server` | The Human implementation: runs Tasks through core, takes input and approvals over HTTP, streams output over SSE |
+| `packages/amsp` | The [Agent API](/agent-api)'s protocol package: the [AMSP](/amsp) wire types, which the Server imports, and a zero-dependency client for Node and browsers |
| `packages/cli` | Terminal client of the Server: REPL and one-shot runs over HTTP and SSE. It starts a local Server when none is running. Only `penguin config` reads and writes configuration files directly through the SDK |
| `packages/web` | Rendering SPA: renders the OmniMessage stream and contains no engine logic |
| `packages/desktop` | Desktop app: an Electron shell that runs the Server as a `utilityProcess` and opens its window on the local HTTP address |
diff --git a/packages/docs/content/architecture.zh.md b/packages/docs/content/architecture.zh.md
index 97e7df53..c914d533 100644
--- a/packages/docs/content/architecture.zh.md
+++ b/packages/docs/content/architecture.zh.md
@@ -36,6 +36,7 @@ CLI 和 Web App 经 HTTP 与 SSE 同 Server 通信。随产品交付的各个应
| --- | --- |
| `packages/core` | SDK 与引擎:`context_engine`、OmniMessage、LLM 与 Environment 接口、钩子、状态和 Trace |
| `packages/server` | Human 实现:通过 core 运行 Task,经 HTTP 接收输入和审批,用 SSE 流式输出结果 |
+| `packages/amsp` | [Agent API](/agent-api) 的协议包:[AMSP](/amsp) 传输类型(Server 也引用)和零依赖的客户端,适用于 Node 与浏览器 |
| `packages/cli` | Server 的终端客户端:REPL 与单次运行都经 HTTP 和 SSE 完成;本地没有运行中的 Server 时会自动启动一个。只有 `penguin config` 直接经 SDK 读写配置文件 |
| `packages/web` | 纯渲染的 SPA:渲染 OmniMessage 流,不含任何引擎逻辑 |
| `packages/desktop` | 桌面应用:一个 Electron 外壳,把 Server 作为 `utilityProcess` 运行,并在本地 HTTP 地址上打开窗口 |
diff --git a/packages/docs/content/chat.en.md b/packages/docs/content/chat.en.md
index f39abfec..f533cb93 100644
--- a/packages/docs/content/chat.en.md
+++ b/packages/docs/content/chat.en.md
@@ -339,7 +339,7 @@ The right-click menu replaces the browser's own menu only on conversation rows a
| --- | --- |
| Turning hourglass | The Session is running |
| Squeezing bar | The Session is compacting |
-| Green dot | A run finished that you have not looked at yet |
+| Green dot | A run finished that you have not looked at yet; only on your own conversations, never in **Background** |
| Small green activity trace | The Session still has background tasks: commands running past their wait time, or background subagents mid-round. The tooltip counts them, such as "2 background tasks" |
| Amber count | Tool calls waiting for approval |
| Pin | The conversation is pinned |
diff --git a/packages/docs/content/chat.zh.md b/packages/docs/content/chat.zh.md
index f704cca0..a06ee0dc 100644
--- a/packages/docs/content/chat.zh.md
+++ b/packages/docs/content/chat.zh.md
@@ -339,7 +339,7 @@ Task 运行时输入了内容,发送按钮的行为取决于 + 菜单底部的
| --- | --- |
| 翻转的沙漏 | Session 正在运行 |
| 向中线合拢的横条 | Session 正在压缩 |
-| 绿点 | 有一次运行已经结束,你还没有查看 |
+| 绿点 | 有一次运行已经结束,你还没有查看;只出现在你自己的对话上,**后台会话**中的会话不显示 |
| 绿色小活动波形 | Session 仍有后台任务:超过等待时间仍在运行的命令,或正在跑一轮的后台子 Agent。悬停提示会显示数量,例如「2 个后台任务」 |
| 琥珀色数字 | 有工具调用等待审批 |
| 置顶标记 | 对话已置顶 |
diff --git a/packages/docs/content/cli.en.md b/packages/docs/content/cli.en.md
index e58cc6b4..9e445ac0 100644
--- a/packages/docs/content/cli.en.md
+++ b/packages/docs/content/cli.en.md
@@ -11,7 +11,7 @@ The CLI is a thin client of the server. Every session-facing command (`run`, `ch
## Server connection
-A CLI that talks to the server on the local machine needs no login. The CLI picks its server in this order, and the first match wins:
+A CLI that talks to the server on the local machine needs no login, except to change an agent's exposure (see [penguin agent api](#penguin-agent-api)). The CLI picks its server in this order, and the first match wins:
1. `--server <url>`: an explicit target.
2. `PENGUIN_API_URL`: the same, from the environment. Server-driven sessions inject it into every tool subprocess, together with `PENGUIN_API_TOKEN`, `PENGUIN_PROJECT_ID`, `PENGUIN_AGENT_ID` and `PENGUIN_SESSION_ID`, so an agent's own `penguin` calls reach the server that runs them.
@@ -20,6 +20,8 @@ A CLI that talks to the server on the local machine needs no login. The CLI pick
The CLI authenticates with the local API token. The server writes a fresh token to `<root>/api-token` on every boot (owner-only), and the CLI sends it as `Authorization: Bearer`. `PENGUIN_API_TOKEN` overrides the file. The CLI reads the file only for loopback targets, so a remote `--server` needs `PENGUIN_API_TOKEN` set explicitly. Holding the file grants admin authority by design, because local filesystem access to the data root already does. `penguin server reset-admin-password` relies on the same rule.
+A few writes take a person's sign-in instead, such as those that change an agent's exposure (see [penguin agent api](#penguin-agent-api)). The server refuses the token on them with `403` `human_required`, and the CLI then sends that request once more with your sign-in from [`penguin auth login`](#penguin-auth-login) or [`penguin auth token`](#penguin-auth-token), stored in `<root>/cli-session.json` and sent as the session cookie. It does so only for a server on this machine, only when the sign-in itself is to a server on this machine, and never from inside a Session, where the command is an agent's. Every other request carries the token alone.
+
## Global conventions
- Model references: a model's identity is always the `(provider, model_id)` pair. `--model-id` takes the upstream model id and `--provider` the group it belongs to. The CLI never infers, guesses or defaults the provider. On `run` and `chat` the pair as a whole is optional: pass both to pick a model, or neither to use the Project's default model. Passing only one is an error.
@@ -206,7 +208,7 @@ penguin logs 402a2e24 -f
## penguin agent
-`agent ls` lists the Project's agents with their id, name, session count and description. `agent create` creates an agent.
+`agent ls` lists the Project's agents with their id, name, session count and description. `agent create` creates an agent. `agent api` manages an agent's API; see [penguin agent api](#penguin-agent-api).
```bash
penguin agent ls [--project-id <id>] [--json] [--server <url>]
@@ -227,6 +229,51 @@ penguin agent ls
penguin agent create --agent-id helper --name "Helper" --plugins software-development,goal
```
+### penguin agent api
+
+Manages an agent's [Agent API](/agent-api), the way its **API** tab does: whether programs may call it, keyless access, the approval mode its API conversations start with, and its keys. Any member can run `status` and `keys ls`; the server takes every change from the Project's owner only, and `server` from an admin only.
+
+Every change also takes a person's sign-in. The server refuses the local API token on them with `human_required`, because every agent's commands carry that token and an agent must not expose itself. Run `penguin auth login` once, or `penguin auth token` on the server's machine; outside a Session the CLI then sends a refused change again with that sign-in. Without one, or when the server no longer accepts it, a change prints that hint and exits 1.
+
+```bash
+penguin agent api status --agent-id <id> [--project-id <id>] [--json] [--server <url>]
+penguin agent api enable --agent-id <id> [--open | --no-open] [--approve <mode>] [...]
+penguin agent api disable --agent-id <id> [...]
+penguin agent api set --agent-id <id> [--open | --no-open] [--approve <mode>] [...]
+penguin agent api keys ls --agent-id <id> [...]
+penguin agent api keys create --agent-id <id> --name <name> [...]
+penguin agent api keys rm <keyId> --agent-id <id> [...]
+penguin agent api server on|off [--json] [--server <url>]
+```
+
+| Command | What it does |
+| --- | --- |
+| `status` | Prints whether the API is on, keyless access, the approval mode, the Base URL (the server's address followed by `/api/amsp/v1`), the Agent ID (`<projectId>/<agentId>`), the number of keys and the server-wide switch. `--json` prints `{agent, baseUrl, api, serverEnabled}` |
+| `enable` | Turns the API on; `--open` / `--no-open` and `--approve` set keyless access and the approval mode in the same request. Prints the status it left |
+| `disable` | Turns the API off. Keyless access, the approval mode and the keys are kept. Prints the status it left |
+| `set` | Changes keyless access or the approval mode and leaves the switch as it is. Given neither, it sends nothing and exits non-zero |
+| `keys ls` | Lists the keys: id, name, prefix, created and last used (`never` until a run uses it). `--json` prints the array |
+| `keys create` | Creates a key. The key alone is printed to stdout, and the confirmation to stderr, so `KEY=$(penguin agent api keys create …)` captures exactly the key. It is shown this once. `--json` prints `{key, secret}` |
+| `keys rm` | Deletes a key by its id; a program presenting it is refused from its next request. An unknown id fails with `key_not_found` |
+| `server` | Turns the Agent API on or off for the whole server (`agentApiEnabled`). Off refuses every agent's API requests and keeps their settings and keys. Any state other than `on` or `off` sends nothing and fails |
+
+Options:
+
+| Option | Description | Default |
+| --- | --- | --- |
+| `--agent-id <id>` | The agent. Required: unlike other commands, it never falls back to `PENGUIN_AGENT_ID` or `default_agent`, so no agent is exposed by default. | — |
+| `--open` / `--no-open` | Allows keyless access / requires a key (`enable`, `set`). | Unchanged |
+| `--approve <mode>` | The approval mode new API conversations start with; see [Approval modes (--approve)](#approval-modes---approve). A mode that asks sends the question to the calling program (`enable`, `set`). An unknown mode fails before any request. | Unchanged |
+| `--name <name>` | The key's name, 1–64 characters (`keys create`, required). | — |
+| `--project-id <id>` / `--json` / `--server <url>` | See [Global conventions](#global-conventions). | — |
+
+```bash
+penguin auth login
+penguin agent api enable --agent-id helper --approve read-only
+KEY=$(penguin agent api keys create --agent-id helper --name ci)
+penguin agent api status --agent-id helper --json
+```
+
## penguin project
`penguin project ls` lists the Projects this account can reach, its own and shared ones, with their id, display name and role. It takes `--json` and `--server`.
@@ -824,7 +871,7 @@ When run interactively, `login` asks for the account first and then the password
### penguin auth status / penguin auth logout
-The session is stored in `<root>/cli-session.json` with mode 0600. `login` writes it, and so does `token` when a server is running on the data root. `status` reads it. `logout` revokes the session and deletes the file: it tells the server first, so the session ends on the server rather than merely being forgotten locally. If the server cannot be reached, `logout` says so and deletes the local file anyway.
+The session is stored in `<root>/cli-session.json` with mode 0600. `login` writes it, and so does `token` when a server is running on the data root. `status` reads it. Outside a Session, the other commands send it to a server on this machine only to repeat a request the server refused to the local API token with `human_required`; see [Server connection](#server-connection). `logout` revokes the session and deletes the file: it tells the server first, so the session ends on the server rather than merely being forgotten locally. If the server cannot be reached, `logout` says so and deletes the local file anyway.
## penguin update
diff --git a/packages/docs/content/cli.zh.md b/packages/docs/content/cli.zh.md
index 2557c082..17b34f6a 100644
--- a/packages/docs/content/cli.zh.md
+++ b/packages/docs/content/cli.zh.md
@@ -11,7 +11,7 @@ CLI 是服务器的瘦客户端。所有面向会话的命令(`run`、`chat`
## 服务器连接
-与本机服务器通信的 CLI 无需登录。CLI 按以下顺序确定要连接的服务器,命中第一项即停止:
+与本机服务器通信的 CLI 无需登录,只有改变 Agent 的对外暴露时例外(见 [penguin agent api](#penguin-agent-api))。CLI 按以下顺序确定要连接的服务器,命中第一项即停止:
1. `--server <url>`:显式指定的目标。
2. `PENGUIN_API_URL`:同样指定目标,但取自环境变量。服务器驱动的会话会把它注入每个工具子进程,同时注入的还有 `PENGUIN_API_TOKEN`、`PENGUIN_PROJECT_ID`、`PENGUIN_AGENT_ID` 和 `PENGUIN_SESSION_ID`,这样 Agent 自己调用 `penguin` 时,请求就能到达运行它的那台服务器。
@@ -20,6 +20,8 @@ CLI 是服务器的瘦客户端。所有面向会话的命令(`run`、`chat`
CLI 使用本地 API token 认证。服务器每次启动都会把一个新 token 写入 `<root>/api-token`(仅所有者可读),CLI 以 `Authorization: Bearer` 的形式发送它。`PENGUIN_API_TOKEN` 优先于这个文件。CLI 只对回环地址目标读取这个文件,因此远程 `--server` 需要显式设置 `PENGUIN_API_TOKEN`。按设计,持有这个文件就等于持有管理员权限——能直接访问数据根目录的本地文件系统,本来就拥有同样的权限。`penguin server reset-admin-password` 依据的也是同一条规则。
+少数修改只接受人的登录,例如改变 Agent 对外暴露的修改(见 [penguin agent api](#penguin-agent-api))。服务器以 `403` `human_required` 拒绝携带 token 的这类请求,CLI 随即改用你通过 [`penguin auth login`](#penguin-auth-login) 或 [`penguin auth token`](#penguin-auth-token) 保存的登录把同一请求再发一次:登录存放在 `<root>/cli-session.json`,以会话 Cookie 发送。CLI 只对本机上的服务器这样做,只在登录的对象本身就是本机服务器时使用,且从不在 Session 内使用——那里的命令属于 Agent。其余请求一律只带 token。
+
## 全局约定
- 模型引用:模型的标识始终是 `(provider, model_id)` 这一对。`--model-id` 接收上游模型 id,`--provider` 接收模型所属的分组。CLI 从不推断、猜测或默认指定供应商。在 `run` 和 `chat` 上,这一对参数整体可选:两个都传即可选择模型,两个都不传则使用 Project 的默认模型;只传一个是错误。
@@ -206,7 +208,7 @@ penguin logs 402a2e24 -f
## penguin agent
-`agent ls` 列出 Project 的 Agent,包括 id、名称、会话数和描述。`agent create` 创建 Agent。
+`agent ls` 列出 Project 的 Agent,包括 id、名称、会话数和描述。`agent create` 创建 Agent。`agent api` 管理 Agent 的 API,见 [penguin agent api](#penguin-agent-api)。
```bash
penguin agent ls [--project-id <id>] [--json] [--server <url>]
@@ -227,6 +229,51 @@ penguin agent ls
penguin agent create --agent-id helper --name "Helper" --plugins software-development,goal
```
+### penguin agent api
+
+管理 Agent 的 [Agent API](/agent-api),作用与它的 **API** 标签页相同:是否允许程序调用、无密钥访问、API 会话起始的审批模式,以及密钥。任何成员都能执行 `status` 和 `keys ls`;所有修改,服务器只接受 Project 所有者发起,`server` 只接受管理员发起。
+
+所有修改还需要人的登录。服务器以 `human_required` 拒绝携带本地 API token 的修改:每个 Agent 的命令都带着这个 token,而 Agent 不得自行对外开放。先运行一次 `penguin auth login`,或在服务器本机运行 `penguin auth token`;此后在 Session 之外,被拒的修改会由 CLI 带着这个登录再发一次。没有登录,或服务器不再接受它时,修改命令打印这条提示并以退出码 1 退出。
+
+```bash
+penguin agent api status --agent-id <id> [--project-id <id>] [--json] [--server <url>]
+penguin agent api enable --agent-id <id> [--open | --no-open] [--approve <mode>] [...]
+penguin agent api disable --agent-id <id> [...]
+penguin agent api set --agent-id <id> [--open | --no-open] [--approve <mode>] [...]
+penguin agent api keys ls --agent-id <id> [...]
+penguin agent api keys create --agent-id <id> --name <name> [...]
+penguin agent api keys rm <keyId> --agent-id <id> [...]
+penguin agent api server on|off [--json] [--server <url>]
+```
+
+| 命令 | 作用 |
+| --- | --- |
+| `status` | 打印 API 是否开启、无密钥访问、审批模式、Base URL(服务器地址加上 `/api/amsp/v1`)、Agent ID(`<projectId>/<agentId>`)、密钥数量和服务器总开关。`--json` 打印 `{agent, baseUrl, api, serverEnabled}` |
+| `enable` | 开启 API;`--open` / `--no-open` 和 `--approve` 在同一个请求里设置无密钥访问和审批模式。打印执行后的状态 |
+| `disable` | 关闭 API。无密钥访问、审批模式和密钥都会保留。打印执行后的状态 |
+| `set` | 修改无密钥访问或审批模式,不改变开关。两者都没给时不发送任何请求,以非零码退出 |
+| `keys ls` | 列出密钥:id、名称、前缀、创建时间和最近使用时间(尚未被运行使用时为 `从未`)。`--json` 打印数组 |
+| `keys create` | 新建密钥。stdout 上只有密钥本身,确认信息写到 stderr,所以 `KEY=$(penguin agent api keys create …)` 恰好取到密钥。密钥只显示这一次。`--json` 打印 `{key, secret}` |
+| `keys rm` | 按 id 删除密钥;出示它的程序从下一个请求起即被拒绝。id 不存在时以 `key_not_found` 失败 |
+| `server` | 为整台服务器开启或关闭 Agent API(`agentApiEnabled`)。关闭后所有 Agent 的 API 请求都被拒绝,各 Agent 的设置和密钥保留。`on`、`off` 以外的状态不发送任何请求,直接失败 |
+
+选项:
+
+| 选项 | 说明 | 默认值 |
+| --- | --- | --- |
+| `--agent-id <id>` | 目标 Agent。必填:与其他命令不同,它不会回退到 `PENGUIN_AGENT_ID` 或 `default_agent`,任何 Agent 都不会因默认值而被对外开放。 | — |
+| `--open` / `--no-open` | 允许无密钥访问 / 要求密钥(`enable`、`set`)。 | 不变 |
+| `--approve <mode>` | 新建 API 会话起始的审批模式,见[审批模式(--approve)](#审批模式--approve)。需要确认时,确认请求发给调用方程序(`enable`、`set`)。模式未知时,在发出任何请求之前失败。 | 不变 |
+| `--name <name>` | 密钥名称,1–64 个字符(`keys create`,必填)。 | — |
+| `--project-id <id>` / `--json` / `--server <url>` | 见[全局约定](#全局约定)。 | — |
+
+```bash
+penguin auth login
+penguin agent api enable --agent-id helper --approve read-only
+KEY=$(penguin agent api keys create --agent-id helper --name ci)
+penguin agent api status --agent-id helper --json
+```
+
## penguin project
`penguin project ls` 列出这个账号能访问的 Project——自己的和共享的——包括 id、显示名称和角色。支持 `--json` 和 `--server`。
@@ -824,7 +871,7 @@ penguin auth token # no password: minted from this data roo
### penguin auth status / penguin auth logout
-会话保存在 `<root>/cli-session.json`,文件权限为 0600。`login` 写入它;数据根目录上有服务器在运行时,`token` 也会写入。`status` 读取它。`logout` 吊销会话并删除文件:它会先通知服务器,因此会话在服务器端结束,而不只是本地把它忘掉。连不上服务器时,`logout` 会说明情况,然后照样删除本地文件。
+会话保存在 `<root>/cli-session.json`,文件权限为 0600。`login` 写入它;数据根目录上有服务器在运行时,`token` 也会写入。`status` 读取它。在 Session 之外,其他命令只在本机上的服务器以 `human_required` 拒绝本地 API token 时才发送它,用来把被拒的请求再发一次,见[服务器连接](#服务器连接)。`logout` 吊销会话并删除文件:它会先通知服务器,因此会话在服务器端结束,而不只是本地把它忘掉。连不上服务器时,`logout` 会说明情况,然后照样删除本地文件。
## penguin update
diff --git a/packages/docs/content/omni-message.en.md b/packages/docs/content/omni-message.en.md
index 382e40bb..6c8b59f0 100644
--- a/packages/docs/content/omni-message.en.md
+++ b/packages/docs/content/omni-message.en.md
@@ -448,6 +448,8 @@ The payload is opaque to PenguinHarness: it passes through and persists verbatim
| Trace on disk | `session_meta` + complete `model_msg` + all `event_msg` (no partials, no `origin`-tagged messages) |
| Server SSE stream | same as the SDK boundary, verbatim single-line JSON — see [Server API](/server-api) |
+The [Agent API](/agent-api) does not stream OmniMessage: its stream is [AMSP](/amsp), a projection the server makes of the same live stream for programs outside PenguinHarness. Nothing in OmniMessage changes for it: no field, type or value is added.
+
How messages travel along these surfaces, and every ordering guarantee, is covered on [Message Flow & Ordering](/message-flow).
## Builders and guards
diff --git a/packages/docs/content/omni-message.zh.md b/packages/docs/content/omni-message.zh.md
index 7022b3b5..16fd4139 100644
--- a/packages/docs/content/omni-message.zh.md
+++ b/packages/docs/content/omni-message.zh.md
@@ -448,6 +448,8 @@ type StopReason = "completed" | "aborted" | "retryable" | "fatal";
| 落盘的 Trace | `session_meta` + 完整 `model_msg` + 全部 `event_msg`(不存分片,也不存带 `origin` 的消息) |
| Server 的 SSE 推送 | 与 SDK 边界相同,原样的单行 JSON,见 [Server API](/server-api) |
+[Agent API](/agent-api) 不推送 OmniMessage,它的事件流是 [AMSP](/amsp):服务器为 PenguinHarness 之外的程序,对同一条实时流所做的投影。OmniMessage 不因此改变,没有新增任何字段、类型或取值。
+
消息沿这些通道传递的机制与各项顺序保证,见[消息流转与时序](/message-flow)。
## 构造与判别
diff --git a/packages/docs/content/security.en.md b/packages/docs/content/security.en.md
index 291e30c3..1ce79ee2 100644
--- a/packages/docs/content/security.en.md
+++ b/packages/docs/content/security.en.md
@@ -112,6 +112,8 @@ Scripts and the CLI never need a password, because local ownership already outra
When a CLI command runs against a server on this machine, it authenticates with the local API token, which the server writes to `<root>/api-token` at every start. See [CLI Reference](/cli#server-connection).
+The local API token cannot change an agent's exposure: turning an agent's API on, keyless access, its approval mode, its keys and the server-wide Agent API switch take a person's sign-in, because every agent's commands carry that token. The server refuses the token on them with `403` `human_required`, and outside a Session the CLI then sends the request once more with your stored sign-in, if you have one; `penguin auth token`, below, gives the CLI that sign-in. This keeps an agent from exposing itself through the credential the harness hands it; it is not a boundary, since a process running as the data root's OS account can mint a session too. The sandbox is what bounds an agent.
+
A script that needs a session of its own mints one. A session is a row in the data root's `web.db`, so the CLI writes one:
```bash
diff --git a/packages/docs/content/security.zh.md b/packages/docs/content/security.zh.md
index d45a9aa2..de2d8d00 100644
--- a/packages/docs/content/security.zh.md
+++ b/packages/docs/content/security.zh.md
@@ -112,6 +112,8 @@ PenguinHarness 用真实凭据在真实机器上运行 Agent,所以值得弄
CLI 命令访问本机上的服务器时,用本地 API token 认证;服务器每次启动都会把它写入 `<root>/api-token`。参见 [CLI 参考](/cli#服务器连接)。
+本地 API token 不能改变 Agent 的对外暴露:开启 Agent 的 API、无密钥访问、审批模式、密钥,以及整台服务器的 Agent API 开关,都需要人的登录,因为每个 Agent 的命令都带着这个 token。服务器以 `403` `human_required` 拒绝携带 token 的这类请求,在 Session 之外,CLI 随即带着你保存的登录(如果有)把请求再发一次;下文的 `penguin auth token` 能为 CLI 提供这样的登录。这防止 Agent 借 harness 交给它的凭据自行对外开放,但不是边界:以数据根目录所属操作系统账号运行的进程同样能铸造会话。约束 Agent 的是沙盒。
+
脚本需要自己的会话时,就自己铸造一个。会话是数据根目录下 `web.db` 里的一行记录,所以 CLI 直接写入一行:
```bash
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index d56da9c7..13033f4c 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -3,7 +3,7 @@ title: Server API
description: Reference for the PenguinHarness server's HTTP API, covering authentication, every route group, the SSE streaming protocol and DTO type imports.
---
-The PenguinHarness server exposes a same-origin HTTP API that the bundled Web App and any other HTTP client use. This page covers authentication first, then the routes grouped by area, each with a route table followed by details, and ends with the SSE streaming protocol. To start the server, see the [Quickstart](/quickstart).
+The PenguinHarness server exposes a same-origin HTTP API that the bundled Web App and any other HTTP client use. This page covers authentication first, then the routes grouped by area, each with a route table followed by details, and ends with the SSE streaming protocol. To start the server, see the [Quickstart](/quickstart). The API that programs outside PenguinHarness call with an agent's key is on its own page, [Agent API](/agent-api).
## Overview
@@ -42,7 +42,7 @@ The API accepts two credentials: a cookie session and the local API token.
- Cookie session: `penguin_session` (HttpOnly, SameSite=Lax), valid for 30 days with sliding renewal.
- Passwords are stored as scrypt hashes. A session is a row in `auth_sessions`, keyed by the sha256 of a random cookie token; the raw token is never stored. A session survives a restart and renews in place, and logout deletes the row.
- There is no open registration. At startup the server seeds the built-in admin `admin` with a random password, which it hashes and discards without anyone seeing it. Until a password is set, every start prints a first-login link that claims the account. For automation, `PENGUIN_SEED_ADMIN_PASSWORD` pins a known password instead. An admin creates all other accounts.
-- Same-origin only: no CORS middleware is enabled.
+- Same-origin only: no CORS middleware is enabled, except on the Agent API's `/api/amsp/v1`, which answers a preflight from any origin and sends `Access-Control-Allow-Origin: *` on a request that carries `Authorization`. That group takes neither credential above: a request presents the agent's API key, or none when the agent allows keyless access. See [Agent API](/agent-api).
- Routes marked admin only answer other users with `403` `admin_required`.
```bash
@@ -59,6 +59,7 @@ Every protected route also accepts `Authorization: Bearer <token>` with the **lo
- The server mints a fresh token at every boot and writes it to `<root>/api-token` with owner-only permissions (`0600`). The previous boot's token stops working as soon as the new one is minted.
- A valid Bearer token authenticates as the built-in `admin`. This is the authorization model by design: local filesystem access to the data root already is admin authority, since whoever can read `api-token` can also read `web.db` next to it. `penguin server reset-admin-password` relies on the same rule.
- Server-driven sessions inject the current token into every tool subprocess as `PENGUIN_API_TOKEN`, together with `PENGUIN_API_URL`, `PENGUIN_PROJECT_ID`, `PENGUIN_AGENT_ID` and `PENGUIN_SESSION_ID`. That is what authorizes an agent's own `penguin` and API calls to reach the server that runs them.
+- The token cannot change an agent's exposure. `PUT …/agents/:agentId/api`, `POST …/api/keys`, `DELETE …/api/keys/:keyId`, `POST …/api/try`, and a `PUT /api/admin/settings` whose body carries `agentApiEnabled` answer it `403` `human_required` and write nothing; they take a cookie session. It is the same refusal the built-in browser gives the token for choosing a backend and minting a pairing code. The reads stay open to it. Since every tool subprocess holds the token, an agent could otherwise open itself to the network from its own shell. This narrows the credential an agent is handed; it is not a boundary. A process that runs as the data root's OS account outside the sandbox can mint a session itself with `penguin auth token`. The sandbox is the boundary.
- SSE endpoints accept the header like any other route. Consume them with `fetch`, not `EventSource`, which cannot send headers.
- The JSON-only Content-Type check on writes applies to Bearer requests too.
@@ -106,11 +107,11 @@ In desktop mode (a server spawned by the desktop app), every route in this group
## Server Settings (admin only)
-Server-wide proxy, attachment and company-mode settings, and the settings groups plugins declare.
+Server-wide proxy, attachment, company-mode and Agent API settings, and the settings groups plugins declare.
| Method | Path | Description |
| --- | --- | --- |
-| GET | `/api/admin/settings` | Server-wide settings: `{settings: {proxyForApp, proxyForAgent, proxyUrl, attachmentMaxMb, attachmentTotalMb, companyMode}}` |
+| GET | `/api/admin/settings` | Server-wide settings: `{settings: {proxyForApp, proxyForAgent, proxyUrl, attachmentMaxMb, attachmentTotalMb, companyMode, browserExtensionsEnabled, agentApiEnabled}}` |
| PUT | `/api/admin/settings` | Updates settings; omitted fields keep their current value, and an invalid field rejects the whole PUT. Returns the full updated settings |
| GET | `/api/admin/settings/proxy-probe` | The reachability probe's targets: `{targets: [{provider, url}]}`. Makes no request |
| POST | `/api/admin/settings/proxy-probe/:provider` | Probes one target over the server's outbound path, sending no credential: `{probe: {provider, url, outcome, ms, status?}}` |
@@ -163,6 +164,10 @@ Two limits cannot be changed: the number of files per message (20) and the inlin
`companyMode` is the server's **Enable company mode** switch, off by default. A change applies without a restart: while the switch is off, every organization route returns `404` `company_mode_off` and the organization scheduler fires nothing.
+### Agent API switch
+
+`agentApiEnabled` is the server's **Allow the Agent API** switch, on by default. Off, every request under `/api/amsp/v1` but a CORS preflight is refused with `403` `agent_api_disabled`. Each agent's API switch, approval mode and keys are kept, and the routes under [Agent API settings](#agent-api-settings) keep working. A change applies from the next request, with no restart. Changing it takes a sign-in: the local API token may change every other setting here, but a body that carries `agentApiEnabled` is refused to it with `403` `human_required`, and none of that body's fields is written. Every member reads the switch as `serverEnabled` in an agent's API settings. See [The admin switch](/agent-api#the-admin-switch).
+
### Plugin settings
A settings group is a contribution to `PluginConfigProvider.groups`; the sandbox's comes first. Each group in the list carries its schema (`configuration`), its stored values merged onto the defaults with secrets masked, the group whose card it is drawn inside (`parent`), and live status lines (`notices`).
@@ -454,6 +459,9 @@ The paths below omit the `/api/projects/:projectId` prefix, except the two globa
| POST | `/agents/:agentId/hooks/archive` | Installs a hook package from a zip: `{dataBase64, overwrite?}` |
| GET | `/agents/:agentId/hooks/:name/archive` | Exports an installed hook package as a zip |
| DELETE | `/agents/:agentId/hooks/:name` | Uninstalls a hook package |
+| GET / PUT | `/agents/:agentId/api` | The agent's API settings: its switch, keyless access, the approval mode and the keys (PUT is owner only) |
+| POST | `/agents/:agentId/api/keys` | Creates an API key: `{name}` → 201 `{key, secret}` (owner only) |
+| DELETE | `/agents/:agentId/api/keys/:keyId` | Deletes an API key (owner only) |
| GET | `/api/plugins` (global) | The plugin library by category (any signed-in user) |
| GET | `/api/plugins/:plugin/files` (global) | The files one library plugin ships, as text keyed by path (any signed-in user) |
@@ -482,6 +490,38 @@ The paths below omit the `/api/projects/:projectId` prefix, except the two globa
- `GET /api/plugins` returns every library plugin by category, with its Skills' metadata and hook points.
- `GET /api/plugins/:plugin/files` returns everything one library plugin ships, as text keyed by path: each Skill's installable `SKILL.md` and reference files under `skills/<name>/`, and the hook scripts under `hooks/`. The plugin detail view's file browser uses it.
+### Agent API settings
+
+These routes back the agent's **API** tab and `penguin agent api`. The settings belong to this server and live in its database, outside the Agent State and the Project file, so an agent can neither expose itself nor loosen its own approval mode. Any member reads them. Writes and keys are the Project owner's; a member gets `403` `owner_required`. They also take a sign-in: the local API token gets `403` `human_required`, as described under [Local API token (Bearer)](#local-api-token-bearer).
+
+```ts
+interface AgentApiResponse {
+ api: {
+ enabled: boolean; // the API tab's switch; off = every /api/amsp/v1 request for the agent is 404 agent_not_found
+ open: boolean; // keyless access: a request without Authorization is accepted
+ approvalMode: "allow-all" | "deny-all" | "read-only" | "always-ask";
+ keys: AgentApiKeyInfo[];
+ };
+ serverEnabled: boolean; // the admin's agentApiEnabled, readable by every member
+}
+
+interface AgentApiKeyInfo {
+ keyId: string;
+ name: string; // 1-64 characters
+ prefix: string; // the key's first 16 characters
+ createdBy: string; // the owner who created it
+ createdAt: string;
+ lastUsedAt: string | null; // null until a run authenticates with it
+}
+```
+
+- An agent never configured reads as off, keyed and `allow-all`, with no keys.
+- `PUT …/api` takes `{enabled?, open?, approvalMode?}` and answers the whole `AgentApiResponse`. Omitted fields keep their value, and every field is checked before any is written. Each API Session copies `approvalMode` when it is created, so a change applies to API Sessions created afterwards.
+- `POST …/api/keys` takes `{name}` and answers 201 `{key, secret}`. The `secret`, `penguin_` followed by 43 characters, is in this answer and nowhere else: the server stores its SHA-256 and lists the key by `prefix`.
+- `DELETE …/api/keys/:keyId` answers 204, and the key is refused from its next request. An unknown key returns `404` `key_not_found`.
+- `GET /agents` marks each agent with `apiEnabled`, the same switch, which the Agents page shows as an icon. Deleting an agent deletes its API settings and keys; deleting a Project deletes those of all its agents.
+- What a program does with a key is on [Agent API](/agent-api), and the stream it reads is [AMSP](/amsp).
+
## Plugin Registry and Project Plugins
The plugins in this section are server-side packages: modules the server loads into its own module tree, such as the sandbox backends. They are not the library plugins installed on an agent, which are covered under [Plugins and hooks](#plugins-and-hooks). The registry routes are global and open to any signed-in user; the installed-plugin routes belong to one Project.
@@ -669,7 +709,7 @@ The paths below omit the `/api/projects/:projectId` prefix.
- `excludeOrg=1` leaves an organization's desk, ticket and subagent Sessions out of the page and out of the `counts=1` totals together, which is what development mode's list asks for. Any other value is a 400.
- On creation, `modelId` and `provider` go together: send the complete pair to pick a model, or omit both to use the Project's default model. Sending only one is a 400.
- An explicit `workspace` must be an existing directory; it is never created. When omitted, the Workspace is a temporary one created automatically. The approval mode defaults to `allow-all`.
-- `client` is a provenance hint stored on the row: `"cli"` from the CLI, `"web"` by default. The server itself writes `"org"` on an organization's desk and ticket sessions, and a client cannot send that value. Only `excludeOrg` reads it as a filter, and only to drop those rows. An `"org"` row whose Trace records no `source` (written by an older release, or not run yet) reads as a `company` Session.
+- `client` is a provenance hint stored on the row: `"cli"` from the CLI, `"web"` by default. The server itself writes `"org"` on an organization's desk and ticket sessions and `"api"` on a Session an Agent API run created, and a client can send neither. `excludeOrg` reads it to drop the `org` rows, and the Agent API continues only `api` Sessions; see [Agent API](/agent-api#conversations). An `"org"` row whose Trace records no `source` (written by an older release, or not run yet) reads as a `company` Session.
- A Session's `source` says what kind of conversation it is (see [session_meta](/omni-message#sessionmeta)). Its category follows from it: a `company` Session is in no category, archived or not, so a request with `category`, `workspaceGroup` or `counts=1` leaves it out of the page and every total; only the plain list serves it. Otherwise an archived Session is `archived` whatever its source; a `user` Session is `active`, and an `api`, `schedule`, `subagent` or `cli` Session is `background`. A row whose Trace head has not been read yet carries no `source` and counts as `active`.
- On creation, `source` accepts only `"cli"`, which `penguin run` sends. Every other source is the server's own to write, and omitting it creates a `user` Session. The retired `"benchmark"` is still accepted, as `"cli"`.
- `GET /dirs` starts at the home directory when `path` is omitted; an explicit `path` must be absolute. It answers `{path, parent, entries, platform}`: every entry carries its `kind` (`dir` or `file`) and `mtime`, and on Windows an entry the system hides (the hidden attribute: `AppData`, `NTUSER.DAT`) carries `hidden: true`. A bare drive such as `D:` is taken as its root `D:\`. The home request with `places=1` adds what the picker's sidebar shows: `standardFolders` (Desktop, Documents, Downloads and Pictures as the machine resolves them — Windows known folders, Linux XDG user directories — omitted when they could not be read) and `locations` (Windows drives, macOS volumes, the Linux root and its mounts under `/media`, `/run/media` and `/mnt`, each with its `kind` and, when it has one, its `label`). A directory the server may not read answers `403 dir_permission_denied` rather than an empty list — on macOS that is usually a Files and Folders permission the user has not granted.
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index fb3c2c72..1c130ac8 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -3,7 +3,7 @@ title: Server API
description: PenguinHarness 服务器的 HTTP API 参考:认证、全部路由分组、SSE 流式协议和 DTO 类型导入。
---
-PenguinHarness 服务器提供一组同源 HTTP API,内置 Web App 和其他任何 HTTP 客户端用的都是它。本页先讲认证,再按功能分组介绍路由(每组先给路由表,再补充细节),最后讲 SSE 流式协议。启动服务器的方法见[快速开始](/quickstart)。
+PenguinHarness 服务器提供一组同源 HTTP API,内置 Web App 和其他任何 HTTP 客户端用的都是它。本页先讲认证,再按功能分组介绍路由(每组先给路由表,再补充细节),最后讲 SSE 流式协议。启动服务器的方法见[快速开始](/quickstart)。PenguinHarness 之外的程序凭 Agent 的密钥调用的 API 另有专页,见 [Agent API](/agent-api)。
## 概览
@@ -42,7 +42,7 @@ API 接受两种凭证:Cookie 会话和本地 API token。
- Cookie 会话:`penguin_session`(HttpOnly,SameSite=Lax),有效期 30 天,滑动续期。
- 密码以 scrypt 哈希存储。会话是 `auth_sessions` 表中的一行,以随机 Cookie token 的 sha256 为键;原始 token 从不存储。会话重启后依然有效,并在原地续期;登出则删除这一行。
- 不开放注册。启动时,服务器会用一个随机密码初始化内置管理员 `admin`:密码哈希后保存,明文随即丢弃,没有任何人见过它。在设置密码之前,每次启动都会打印一条首次登录链接,用来认领账号。自动化场景可以改用 `PENGUIN_SEED_ADMIN_PASSWORD` 固定一个已知密码。其余所有账号都由管理员创建。
-- 仅限同源:未启用任何 CORS 中间件。
+- 仅限同源:未启用任何 CORS 中间件。例外是 Agent API 的 `/api/amsp/v1`:它应答任何来源的预检,并在带 `Authorization` 的请求上返回 `Access-Control-Allow-Origin: *`。这组路由不接受上面两种凭证:请求出示的是该 Agent 的 API 密钥;Agent 允许无密钥访问时,也可以不出示。见 [Agent API](/agent-api)。
- 标为「仅管理员」的路由,对其他用户一律返回 `403` `admin_required`。
```bash
@@ -59,6 +59,7 @@ curl -c cookies.txt -H "Content-Type: application/json" \
- 服务器每次启动都生成一个新 token,写入 `<root>/api-token`,文件权限仅限所有者(`0600`)。新 token 一经生成,上一次启动的 token 立即失效。
- 有效的 Bearer token 以内置 `admin` 的身份通过认证。这是有意设计的授权模型:在本机文件系统上能访问数据根目录,本身就等于管理员权限,因为能读 `api-token` 的人也能读它旁边的 `web.db`。`penguin server reset-admin-password` 依赖的正是这条规则。
- 服务器驱动的会话会把当前 token 注入每个工具子进程的环境变量 `PENGUIN_API_TOKEN`,同时注入 `PENGUIN_API_URL`、`PENGUIN_PROJECT_ID`、`PENGUIN_AGENT_ID` 和 `PENGUIN_SESSION_ID`。Agent 自己的 `penguin` 命令和 API 调用正是靠这些变量获得授权,才能连上运行自己的服务器。
+- 这个 token 不能改变 Agent 的对外暴露。`PUT …/agents/:agentId/api`、`POST …/api/keys`、`DELETE …/api/keys/:keyId`、`POST …/api/try`,以及请求体带 `agentApiEnabled` 的 `PUT /api/admin/settings`,对它一律答 `403` `human_required`,不写入任何内容;这些路由只接受 Cookie 会话。内置浏览器在选择后端与生成配对码时对它也是同一种拒绝。读取路由对它照常开放。每个工具子进程都持有这个 token,否则 Agent 就能在自己的 shell 里把自己开放到网络上。这收窄了交给 Agent 的凭据,但不是边界:在沙盒之外、以数据根目录所属操作系统账号运行的进程可以用 `penguin auth token` 自行铸造会话。边界是沙盒。
- SSE 端点和其他路由一样接受这个请求头。消费它们要用 `fetch`,不要用 `EventSource`——后者无法发送请求头。
- 写请求只接受 JSON 的 Content-Type 检查,对 Bearer 请求同样生效。
@@ -106,11 +107,11 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
## 服务器设置(仅管理员)
-服务器全局的代理、附件和公司模式设置,以及插件声明的设置分组。
+服务器全局的代理、附件、公司模式和 Agent API 设置,以及插件声明的设置分组。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | `/api/admin/settings` | 服务器全局设置:`{settings: {proxyForApp, proxyForAgent, proxyUrl, attachmentMaxMb, attachmentTotalMb, companyMode}}` |
+| GET | `/api/admin/settings` | 服务器全局设置:`{settings: {proxyForApp, proxyForAgent, proxyUrl, attachmentMaxMb, attachmentTotalMb, companyMode, browserExtensionsEnabled, agentApiEnabled}}` |
| PUT | `/api/admin/settings` | 更新设置;省略的字段保持当前值,任何字段非法都会拒绝整个 PUT。返回更新后的完整设置 |
| GET | `/api/admin/settings/proxy-probe` | 可达性探测的目标:`{targets: [{provider, url}]}`。不发起任何请求 |
| POST | `/api/admin/settings/proxy-probe/:provider` | 经服务器的出站链路探测其中一个目标,不发送任何凭证:`{probe: {provider, url, outcome, ms, status?}}` |
@@ -163,6 +164,10 @@ PUT 按如下规则校验:
`companyMode` 是服务器的**启用公司模式**开关,默认关闭。修改无需重启即生效:开关关闭期间,所有组织路由都返回 `404` `company_mode_off`,组织的调度器也不会触发任何事件。
+### Agent API 开关
+
+`agentApiEnabled` 是服务器的**允许 Agent API** 开关,默认开启。关闭后,`/api/amsp/v1` 下除 CORS 预检以外的所有请求都以 `403` `agent_api_disabled` 拒绝。各 Agent 的 API 开关、审批模式和密钥都会保留,[Agent API 设置](#agent-api-设置)下的路由照常可用。修改从下一个请求起生效,无需重启。修改它需要登录:本地 API token 可以修改这里的其余各项设置,但请求体带 `agentApiEnabled` 时,对它答 `403` `human_required`,该请求体中的字段一项也不写入。所有成员都能从 Agent 的 API 设置中的 `serverEnabled` 读到这个开关。见[管理员开关](/agent-api#管理员开关)。
+
### 插件设置
设置分组是投给 `PluginConfigProvider.groups` 的 contribution,沙盒的排在最前。列表中的每个分组带有它的 schema(`configuration`)、合并到缺省值上的存储值(密钥掩码)、它被画在哪个分组的卡片里(`parent`),以及实时状态行(`notices`)。
@@ -454,6 +459,9 @@ flow id 指向的流程不存在时返回 `404 platform_auth_flow_not_found`。`
| POST | `/agents/:agentId/hooks/archive` | 从 zip 安装钩子包:`{dataBase64, overwrite?}` |
| GET | `/agents/:agentId/hooks/:name/archive` | 将已安装的钩子包导出为 zip |
| DELETE | `/agents/:agentId/hooks/:name` | 卸载一个钩子包 |
+| GET / PUT | `/agents/:agentId/api` | Agent 的 API 设置:开关、无密钥访问、审批模式和密钥(PUT 仅限所有者) |
+| POST | `/agents/:agentId/api/keys` | 新建 API 密钥:`{name}` → 201 `{key, secret}`(仅所有者) |
+| DELETE | `/agents/:agentId/api/keys/:keyId` | 删除 API 密钥(仅所有者) |
| GET | `/api/plugins`(全局) | 按分类返回插件库(任何已登录用户) |
| GET | `/api/plugins/:plugin/files`(全局) | 单个插件库插件自带的所有文件,以路径为键返回文本(任何已登录用户) |
@@ -482,6 +490,38 @@ flow id 指向的流程不存在时返回 `404 platform_auth_flow_not_found`。`
- `GET /api/plugins` 按分类返回插件库的全部插件,包括每个插件的 Skill 元数据和钩子点。
- `GET /api/plugins/:plugin/files` 返回单个插件库插件自带的全部文件,以路径为键返回文本:`skills/<name>/` 下是每个 Skill 可安装的 `SKILL.md` 和参考文件,`hooks/` 下是钩子脚本。插件详情页的文件浏览器用的就是这个路由。
+### Agent API 设置
+
+这组路由支撑 Agent 的 **API** 标签页和 `penguin agent api`。这些设置属于这台服务器,保存在它的数据库里,不在 Agent State 中,也不在 Project 文件中,因此 Agent 既不能自行对外开放,也不能放宽自己的审批模式。任何成员都能读取;修改设置和管理密钥仅限 Project 所有者,成员会得到 `403` `owner_required`。这些修改还需要登录:本地 API token 会得到 `403` `human_required`,见上文「本地 API token(Bearer)」。
+
+```ts
+interface AgentApiResponse {
+ api: {
+ enabled: boolean; // the API tab's switch; off = every /api/amsp/v1 request for the agent is 404 agent_not_found
+ open: boolean; // keyless access: a request without Authorization is accepted
+ approvalMode: "allow-all" | "deny-all" | "read-only" | "always-ask";
+ keys: AgentApiKeyInfo[];
+ };
+ serverEnabled: boolean; // the admin's agentApiEnabled, readable by every member
+}
+
+interface AgentApiKeyInfo {
+ keyId: string;
+ name: string; // 1-64 characters
+ prefix: string; // the key's first 16 characters
+ createdBy: string; // the owner who created it
+ createdAt: string;
+ lastUsedAt: string | null; // null until a run authenticates with it
+}
+```
+
+- 从未配置过的 Agent 读作:关闭、需要密钥、`allow-all`、没有密钥。
+- `PUT …/api` 接受 `{enabled?, open?, approvalMode?}`,返回完整的 `AgentApiResponse`。省略的字段保持原值;所有字段校验通过后才会写入任何一项。每个 API Session 在创建时复制 `approvalMode`,所以修改只影响之后新建的 API Session。
+- `POST …/api/keys` 接受 `{name}`,返回 201 `{key, secret}`。`secret` 形如 `penguin_` 加 43 个字符,只出现在这一次响应里:服务器只保存它的 SHA-256,列表中以 `prefix` 区分密钥。
+- `DELETE …/api/keys/:keyId` 返回 204,该密钥从下一个请求起即被拒绝。密钥不存在时返回 `404` `key_not_found`。
+- `GET /agents` 给每个 Agent 标上 `apiEnabled`,即同一个开关,智能体页面据此显示 API 图标。删除 Agent 会一并删除它的 API 设置和密钥;删除 Project 会删除其下所有 Agent 的这些数据。
+- 程序凭密钥能做什么,见 [Agent API](/agent-api);它读取的事件流见 [AMSP](/amsp)。
+
## 插件注册表与 Project 插件
本节的插件是服务端的包:由服务器加载进自身模块树的模块,例如沙箱后端。它们不是安装在 Agent 上的插件库插件,后者见[插件与钩子](#插件与钩子)。注册表路由是全局的,任何已登录用户都可以访问;已安装插件路由属于单个 Project。
@@ -669,7 +709,7 @@ Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估
- `excludeOrg=1` 会把组织的工位会话、工单会话和子 Session 一并移出这一页以及 `counts=1` 的总数,这正是开发模式的列表所要的。取其他值返回 400。
- 创建时 `modelId` 和 `provider` 必须成对出现:要指定模型就传完整一对,两个都省略则使用 Project 的默认模型。只传一个返回 400。
- 显式传入的 `workspace` 必须是已存在的目录,永远不会自动创建。省略时自动创建一个临时 Workspace。审批模式默认 `allow-all`。
-- `client` 是记录在数据行上的来源提示:CLI 发起的请求为 `"cli"`,默认 `"web"`。组织的工位会话和工单会话由服务器自己写入 `"org"`,客户端不能发送这个值。只有 `excludeOrg` 会把它当作过滤条件,而且只用来剔除这些行。Trace 未记录 `source` 的 `"org"` 行(旧版本写下的,或尚未运行过的)读作 `company` 会话。
+- `client` 是记录在数据行上的来源提示:CLI 发起的请求为 `"cli"`,默认 `"web"`。组织的工位会话和工单会话由服务器自己写入 `"org"`,Agent API 的运行新建的 Session 由服务器写入 `"api"`,这两个值客户端都不能发送。`excludeOrg` 用它剔除 `org` 行,Agent API 只延续 `api` 行;见 [Agent API](/agent-api#会话)。Trace 未记录 `source` 的 `"org"` 行(旧版本写下的,或尚未运行过的)读作 `company` 会话。
- Session 的 `source` 表示它是哪一类会话(见 [session_meta](/omni-message#sessionmeta)),类别由它决定:`company` 会话不属于任何类别,归档与否都一样,因此带 `category`、`workspaceGroup` 或 `counts=1` 的请求会把它移出这一页和所有总数,只有不带这些参数的完整列表才返回它。其余的会话,已归档的无论来源都是 `archived`;`user` 会话为 `active`,`api`、`schedule`、`subagent`、`cli` 会话为 `background`。Trace 开头尚未读过的行不带 `source`,按 `active` 计。
- 创建时 `source` 只接受 `"cli"`,由 `penguin run` 发送;其他来源只由服务器自己写入,省略时创建 `user` 会话。已停用的 `"benchmark"` 仍然接受,按 `"cli"` 处理。
- `GET /dirs` 省略 `path` 时从主目录开始;显式传入的 `path` 必须是绝对路径。响应为 `{path, parent, entries, platform}`:每个条目带 `kind`(`dir` 或 `file`)与 `mtime`;在 Windows 上,系统隐藏的条目(带隐藏属性,如 `AppData`、`NTUSER.DAT`)另带 `hidden: true`,只写盘符如 `D:` 即视为其根目录 `D:\`。请求主目录并带 `places=1` 时,另附选择器左栏所需的两项:`standardFolders`(桌面、文档、下载、图片,按该机器自己的规则取得——Windows 的已知文件夹、Linux 的 XDG 用户目录;读取失败时省略)与 `locations`(Windows 的各盘符、macOS 的各卷、Linux 的根目录及 `/media`、`/run/media`、`/mnt` 下的挂载点,各带 `kind`,有名称时带 `label`)。服务无权读取的目录返回 `403 dir_permission_denied`,不再按空列表返回;在 macOS 上这通常是用户尚未授予的「文件与文件夹」权限。
diff --git a/packages/docs/content/settings.en.md b/packages/docs/content/settings.en.md
index 112b2ce0..cd33b036 100644
--- a/packages/docs/content/settings.en.md
+++ b/packages/docs/content/settings.en.md
@@ -1,12 +1,12 @@
---
title: Settings
-description: Manage your profile, preferences and password, and, as an admin, users, the proxy, upload limits, company mode and plugins.
+description: Manage your profile, preferences and password, and, as an admin, users, the proxy, upload limits, company mode, the Agent API and plugins.
---
-**Settings** is one dialog for the settings that belong to neither a Project nor an agent: your profile, your interface preferences and password, and, for an admin, the server's users, proxy, upload limits, company mode and plugins, the sandbox among them.
+**Settings** is one dialog for the settings that belong to neither a Project nor an agent: your profile, your interface preferences and password, and, for an admin, the server's users, proxy, upload limits, company mode, Agent API and plugins, the sandbox among them.
- Your own settings: [Profile](#profile), [General](#general), [Appearance](#appearance), [Keyboard shortcuts](#keyboard-shortcuts) and [Account](#account).
-- Server settings, for admins: [Users](#users), [Proxy options](#proxy-options), [Upload limits](#upload-limits), [Company mode](#company-mode) and [Plugins](#plugins).
+- Server settings, for admins: [Users](#users), [Proxy options](#proxy-options), [Upload limits](#upload-limits), [Company mode](#company-mode), [Agent API](#agent-api) and [Plugins](#plugins).
## Open Settings
@@ -30,6 +30,7 @@ The rail is grouped into **Personal** and **Server**:
| [Proxy options](#proxy-options) | Server | Admin only |
| [Upload limits](#upload-limits) | Server | Admin only |
| [Company mode](#company-mode) | Server | Admin only |
+| [Agent API](#agent-api) | Server | Admin only |
| [Plugins](#plugins) | Server | Admin only |
Personal preferences apply the moment they are touched. There is no Save button and nothing to lose by closing the dialog. The nickname on the Profile page is the one exception: typed text needs a commit, and its **Save** sits beside the field rather than under the page.
@@ -261,6 +262,14 @@ Turning it off stops the organization scheduler and every organization route, an
> [!NOTE]
> Company mode is a beta. See [Company mode](/company-mode).
+## Agent API
+
+The **Agent API** page (**Settings › Server › Agent API**) is admin-only and server-global. It holds the **Allow the Agent API** switch, on by default, over every agent's API: the HTTP API through which programs outside PenguinHarness talk to an agent (see [Agent API](/agent-api)).
+
+The switch applies the moment it is flipped. There is no Save button.
+
+Turning it off asks first, because every program calling an agent fails from then on. Once it is off, every Agent API request is refused with `403` `agent_api_disabled`. Each agent's own switch, approval mode and keys are kept, and work again when the switch is back on. Meanwhile each agent's **API** tab shows its switch disabled, with a note saying why, to every member.
+
## Plugins
The **Plugins** page is admin-only and server-global. It shows the options each loaded plugin declares, as a form drawn from the plugin's own schema. A plugin that declares no options has no card here. A save reaches the plugin at once, with no restart.
diff --git a/packages/docs/content/settings.zh.md b/packages/docs/content/settings.zh.md
index ef8e70f4..d6cd6e50 100644
--- a/packages/docs/content/settings.zh.md
+++ b/packages/docs/content/settings.zh.md
@@ -1,12 +1,12 @@
---
title: 设置
-description: 管理个人资料、偏好设置和密码;管理员还可以管理用户、代理、上传限制、公司模式和插件。
+description: 管理个人资料、偏好设置和密码;管理员还可以管理用户、代理、上传限制、公司模式、Agent API 和插件。
---
-**设置**把不属于 Project 也不属于 Agent 的设置集中在一个对话框里:你的个人资料、界面偏好和密码;管理员还能在这里管理服务器的用户、代理、上传限制、公司模式和插件(包括沙盒)。
+**设置**把不属于 Project 也不属于 Agent 的设置集中在一个对话框里:你的个人资料、界面偏好和密码;管理员还能在这里管理服务器的用户、代理、上传限制、公司模式、Agent API 和插件(包括沙盒)。
- 个人设置:[个人资料](#个人资料)、[通用](#通用)、[外观](#外观)、[快捷键](#快捷键)和[账户](#账户)。
-- 服务器设置,仅管理员:[用户管理](#用户管理)、[代理选项](#代理选项)、[上传限制](#上传限制)、[公司模式](#公司模式)和[插件](#插件)。
+- 服务器设置,仅管理员:[用户管理](#用户管理)、[代理选项](#代理选项)、[上传限制](#上传限制)、[公司模式](#公司模式)、[Agent API](#agent-api) 和[插件](#插件)。
## 打开设置
@@ -30,6 +30,7 @@ description: 管理个人资料、偏好设置和密码;管理员还可以管
| [代理选项](#代理选项) | 服务器 | 仅管理员 |
| [上传限制](#上传限制) | 服务器 | 仅管理员 |
| [公司模式](#公司模式) | 服务器 | 仅管理员 |
+| [Agent API](#agent-api) | 服务器 | 仅管理员 |
| [插件](#插件) | 服务器 | 仅管理员 |
个人偏好改动即生效,没有保存按钮,关掉对话框也不会丢失什么。唯一的例外是个人资料页的昵称:输入的文字需要显式提交,它的**保存**按钮就在输入框旁边,不在页面底部。
@@ -261,6 +262,14 @@ Trace 会成为该 Agent 的一段新对话。如果该 Agent 下已有相同 id
> [!NOTE]
> 公司模式是内测功能。见[公司模式](/company-mode)。
+## Agent API
+
+**Agent API** 页(**设置 › 服务器 › Agent API**)仅管理员可见,作用于整台服务器。页面上只有**允许 Agent API** 这一个开关,默认开启,统管所有 Agent 的 API,也就是 PenguinHarness 之外的程序与 Agent 对话所用的 HTTP API(见 [Agent API](/agent-api))。
+
+开关一拨即生效,没有保存按钮。
+
+关闭前会先确认,因为此后所有调用 Agent 的程序都会失败。关闭后,所有 Agent API 请求都以 `403` `agent_api_disabled` 拒绝。各 Agent 自己的开关、审批模式和密钥都会保留,重新开启后照常可用。在此期间,各 Agent 的 **API** 标签页对所有成员显示为开关不可用,并附说明。
+
## 插件
**插件**页仅管理员可见,作用于整台服务器。页面列出每个已装载插件声明的选项,表单按插件自己的 schema 生成;没有声明选项的插件不会出现。保存后立即送达插件,无需重启。
diff --git a/packages/docs/content/skills.en.md b/packages/docs/content/skills.en.md
index ddd22824..42c1eb90 100644
--- a/packages/docs/content/skills.en.md
+++ b/packages/docs/content/skills.en.md
@@ -230,7 +230,7 @@ The built-in plugins, by category (`PLUGIN_CATEGORIES` in `packages/core/src/plu
| Software Development | `software-development` | Software development end to end, with two Skills: `software-engineering` (investigate, implement and validate with minimal scope) and `web-design` (the Penguin visual language for generated web UIs) |
| | `use-claude-code` | Run Claude Code on a remote host over SSH: a persistent expect session, headless `-p` with the stdin fix, a tmux-driven interactive TUI and multi-turn continuity (not preinstalled: install from the library when needed) |
| | `wechat-miniprogram` | Take a WeChat mini-program from code to published on a headless Linux server: QR login to mp.weixin.qq.com, switching from a public account to the mini-program backend, the AppID and upload key, IP whitelisting, upload with miniprogram-ci, a verified preview QR, the mandatory user-privacy policy, review and release (not preinstalled) |
-| AI App Development | `agent-development` | Agent development on PenguinHarness, with four Skills: `penguin-sdk` (build agent/AI/RAG apps on the SDK), `unified-llm-api` (call model APIs through `@prismshadow/agenthub`), `penguin-config` (manage model keys, defaults and Vault secrets) and `penguin-orchestration` (drive agents, Sessions, costs and schedules from a shell) |
+| AI App Development | `agent-development` | Agent development on Adelie, with four Skills: `penguin-sdk` (build agent/AI/RAG apps on the SDK, or connect a program to an agent over the Agent API; it asks which way first), `unified-llm-api` (call model APIs through `@prismshadow/agenthub`), `penguin-config` (manage model keys, defaults and Vault secrets) and `penguin-orchestration` (drive agents, Sessions, costs and schedules from a shell) |
| | `model-development` | Model development on your own hardware, with three Skills: `llamafactory` (fine-tune), `ollama` (run local models) and `vllm` (serve behind an OpenAI-compatible endpoint) |
| | `skill-porting` | Port Skills from external sources (plugin marketplaces, skills.sh registries, GitHub repos or local folders) into the agent after review and normalization |
| | `agent-tuning` | The tuning loop as four Skills: `agent-initialization` (set an agent up from a requirement), `benchmark-design` (design and calibrate a capability Benchmark), `agent-evaluation` (execute and score one isolated case) and `agent-optimization` (improve the agent from measured results) |
diff --git a/packages/docs/content/skills.zh.md b/packages/docs/content/skills.zh.md
index da2594e3..d63ee2f9 100644
--- a/packages/docs/content/skills.zh.md
+++ b/packages/docs/content/skills.zh.md
@@ -230,7 +230,7 @@ Agent 可以在 Task 中重写自己的 `SKILL.md`。结合 Benchmark 评估和
| 软件开发 | `software-development` | 端到端的软件开发,包含两个 Skill:`software-engineering`(在最小范围内调查、实现和验证)和 `web-design`(生成 Web UI 用的 Penguin 视觉语言) |
| | `use-claude-code` | 通过 SSH 在远程主机上运行 Claude Code:持久 expect 会话、带 stdin 修复的无头 `-p` 模式、tmux 驱动的交互式 TUI,以及多轮连续性(不预装:需要时从插件库安装) |
| | `wechat-miniprogram` | 在无桌面的 Linux 服务器上把微信小程序从代码做到发布:扫码登录 mp.weixin.qq.com、从公众号后台切到小程序后台、取 AppID 与上传密钥、加 IP 白名单、用 miniprogram-ci 上传、交付校验过的预览码、填写必填的用户隐私保护指引、提交审核与发布(不预装) |
-| AI 应用开发 | `agent-development` | PenguinHarness 上的 Agent 开发,包含四个 Skill:`penguin-sdk`(基于 SDK 构建 Agent/AI/RAG 应用)、`unified-llm-api`(通过 `@prismshadow/agenthub` 调用模型 API)、`penguin-config`(管理模型密钥、默认值和 Vault 机密)和 `penguin-orchestration`(在 shell 里驱动 Agent、Session、成本和定时任务) |
+| AI 应用开发 | `agent-development` | Adelie 上的 Agent 开发,包含四个 Skill:`penguin-sdk`(基于 SDK 构建 Agent/AI/RAG 应用,或经 Agent API 把程序接入 Agent;动手前先问用哪种方式)、`unified-llm-api`(通过 `@prismshadow/agenthub` 调用模型 API)、`penguin-config`(管理模型密钥、默认值和 Vault 机密)和 `penguin-orchestration`(在 shell 里驱动 Agent、Session、成本和定时任务) |
| | `model-development` | 在自己的硬件上做模型开发,包含三个 Skill:`llamafactory`(微调)、`ollama`(运行本地模型)和 `vllm`(在 OpenAI 兼容端点后面提供服务) |
| | `skill-porting` | 把外部来源(插件市场、skills.sh 注册表、GitHub 仓库或本地文件夹)的 Skill 经审查和规范化后移植到 Agent |
| | `agent-tuning` | 用四个 Skill 构成调优闭环:`agent-initialization`(根据需求搭建 Agent)、`benchmark-design`(设计和校准能力 Benchmark)、`agent-evaluation`(隔离执行单个题目并打分)和 `agent-optimization`(根据实测结果改进 Agent) |
diff --git a/packages/docs/src/lib/nav.ts b/packages/docs/src/lib/nav.ts
index 9872c6d4..0d791c40 100644
--- a/packages/docs/src/lib/nav.ts
+++ b/packages/docs/src/lib/nav.ts
@@ -75,7 +75,10 @@ export const DOCS_NAV: DocsSectionDef[] = [
"sessions-and-traces",
),
},
- { id: "reference", pages: pages("cli", "server-api", "configuration", "security") },
+ {
+ id: "reference",
+ pages: pages("cli", "server-api", "agent-api", "amsp", "configuration", "security"),
+ },
];
/** All slugs in display order — each parent immediately followed by its children. */
diff --git a/packages/server/package.json b/packages/server/package.json
index f91e1827..b29330d1 100644
--- a/packages/server/package.json
+++ b/packages/server/package.json
@@ -71,6 +71,7 @@
"dependencies": {
"@hono/node-server": "^2.0.5",
"@larksuiteoapi/node-sdk": "^1.73.0",
+ "@lmliheng/amsp": "workspace:*",
"@lmliheng/penguin-core": "workspace:*",
"@xterm/headless": "^5.5.0",
"dotenv": "^17.0.0",
diff --git a/packages/server/src/amsp/cors.ts b/packages/server/src/amsp/cors.ts
new file mode 100644
index 00000000..b74c1e49
--- /dev/null
+++ b/packages/server/src/amsp/cors.ts
@@ -0,0 +1,37 @@
+/**
+ * The Agent API's CORS rule: a preflight is always answered; `Access-Control-Allow-Origin: *`
+ * goes only on requests that carry `Authorization`. A keyless request gets no CORS header, so a
+ * page on another origin cannot drive an open Agent from a visitor's browser (on a loopback
+ * server, the drive-by that keyless access would otherwise invite).
+ *
+ * The public group runs it first (routes.ts). The host layer (src/app.ts) and `HttpModule` also
+ * run the header half ahead of their `/api/*` body cap and JSON-only-writes guard, whose 413 and
+ * 415 answer before the group is reached: without it, a browser caller would read those refusals
+ * as a CORS failure.
+ */
+import type { MiddlewareHandler } from "hono";
+
+/** Where the public group is mounted; the wire version is in the path. */
+export const AMSP_PREFIX = "/api/amsp/v1";
+
+const PREFLIGHT_HEADERS = {
+ "Access-Control-Allow-Origin": "*",
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
+ "Access-Control-Allow-Headers": "Authorization, Content-Type",
+ "Access-Control-Max-Age": "600",
+};
+
+/**
+ * `Access-Control-Allow-Origin: *` on a request that carries `Authorization`, set before the
+ * rest of the chain runs, so a streamed response and an error answer carry it too.
+ */
+export const amspAllowOrigin: MiddlewareHandler = async (c, next) => {
+ if (c.req.header("authorization") !== undefined) c.header("Access-Control-Allow-Origin", "*");
+ await next();
+};
+
+/** The whole rule, as the group runs it: the preflight answered here, every other request headed. */
+export const amspCors: MiddlewareHandler = async (c, next) => {
+ if (c.req.method === "OPTIONS") return c.body(null, 204, PREFLIGHT_HEADERS);
+ return amspAllowOrigin(c, next);
+};
diff --git a/packages/server/src/amsp/gate.ts b/packages/server/src/amsp/gate.ts
new file mode 100644
index 00000000..7aab43d4
--- /dev/null
+++ b/packages/server/src/amsp/gate.ts
@@ -0,0 +1,140 @@
+/**
+ * The `/api/amsp/v1` gate: who a request is for, and whether it may be made — decided before the
+ * body is read. In order:
+ *
+ * 1. the admin switch: off answers every request 403 `agent_api_disabled` (the CORS preflight
+ * is answered before this gate runs);
+ * 2. the path names an Agent (`/agents/:projectId/:agentId…`) or an API Session
+ * (`/sessions/:sessionId…`): an invalid id, an Agent whose API switch is off or that does not
+ * exist, a Session no API run created, or one whose Agent's switch is off, is a 404 that says
+ * nothing about which of these it was;
+ * 3. the caller: an `Authorization` header must carry a key of that Agent — an unknown key is
+ * 401, another Agent's key the same 404 as an unknown Agent (or Session); no header at all is
+ * accepted only when the Agent allows keyless access, 401 otherwise.
+ *
+ * Any other path under the prefix passes through untouched, to the group's 404 tail.
+ *
+ * The first two checks are also the API tab's try route's (try-route.ts), which stands the
+ * owner's sign-in where the key would be.
+ */
+import { isValidId } from "@lmliheng/penguin-core";
+import type { MiddlewareHandler } from "hono";
+import type { AppEnv } from "../auth/middleware.js";
+import { bearerToken } from "../auth/middleware.js";
+import type { SessionRow } from "../db/repos/sessions.js";
+import { HttpError } from "../http/errors.js";
+import type { AgentApi, AgentApiRow } from "../mechanisms/agent-api.js";
+import type { AgentConfig } from "../mechanisms/agents.js";
+import type { SessionIndex } from "../mechanisms/sessions.js";
+import type { Settings } from "../mechanisms/settings.js";
+import { hashAgentApiKey } from "./keys.js";
+
+/** What the gate resolved a request to: the Agent it is for, the key it presented, the Session it names. */
+export interface AmspContext {
+ projectId: string;
+ agentId: string;
+ /** The key that authenticated the request; null for a keyless request to an open Agent. */
+ keyId: string | null;
+ /** The API Session a `/sessions/:sessionId…` path names; null on an Agent path. */
+ session: SessionRow | null;
+}
+
+/** The group's Hono env: the app's, plus the gate's resolution. */
+export type AmspEnv = { Variables: AppEnv["Variables"] & { amsp: AmspContext } };
+
+export interface AmspGateDeps {
+ settings: Pick<Settings, "getAgentApiEnabled">;
+ agentApi: AgentApi;
+ sessions: Pick<SessionIndex, "findById">;
+ agentConfig: Pick<AgentConfig, "exists">;
+}
+
+/** One answer for an Agent that does not exist, is not exposed, or is not the key's. */
+export const agentNotFound = (): HttpError =>
+ new HttpError(404, "agent_not_found", "No Agent with this id has its API enabled.");
+
+/** One answer for a Session that does not exist, is not an API Session, or is not the key's Agent's. */
+export const sessionNotFound = (): HttpError =>
+ new HttpError(404, "session_not_found", "No API Session with this id.");
+
+const unauthorized = (message: string): HttpError => new HttpError(401, "unauthorized", message);
+
+/** The admin's switch: off refuses every request 403 `agent_api_disabled`. */
+export function requireAgentApiOn(settings: Pick<Settings, "getAgentApiEnabled">): void {
+ if (!settings.getAgentApiEnabled()) {
+ throw new HttpError(403, "agent_api_disabled", "The Agent API is turned off on this server.");
+ }
+}
+
+/**
+ * The Agent a path names, once it is exposed: valid ids, its API switch on, and the Agent there.
+ * Anything else is the one 404 `agent_not_found`, which says nothing about which it was.
+ */
+export async function requireExposedAgent(
+ deps: Pick<AmspGateDeps, "agentApi" | "agentConfig">,
+ projectId: string,
+ agentId: string,
+): Promise<AgentApiRow> {
+ if (!isValidId(projectId) || !isValidId(agentId)) throw agentNotFound();
+ const api = deps.agentApi.get(projectId, agentId);
+ if (api === null || !api.enabled) throw agentNotFound();
+ if (!(await deps.agentConfig.exists(projectId, agentId))) throw agentNotFound();
+ return api;
+}
+
+/** The path below the group prefix, split into decoded segments; null when a segment does not decode. */
+function segmentsOf(path: string, prefix: string): string[] | null {
+ const rest = path.startsWith(prefix) ? path.slice(prefix.length) : path;
+ try {
+ return rest
+ .split("/")
+ .filter((s) => s !== "")
+ .map((s) => decodeURIComponent(s));
+ } catch {
+ return null;
+ }
+}
+
+export function amspGate(prefix: string, deps: AmspGateDeps): MiddlewareHandler<AmspEnv> {
+ /**
+ * The caller, against the Agent's settings: the key it presents (null when it presents none),
+ * or the refusal. `notTheKeys` is the 404 a key of another Agent gets.
+ */
+ const authenticate = (
+ header: string | undefined,
+ api: AgentApiRow,
+ notTheKeys: () => HttpError,
+ ): string | null => {
+ if (header === undefined) {
+ if (!api.open) throw unauthorized("This Agent requires an API key.");
+ return null;
+ }
+ const token = bearerToken(header);
+ const key = token === null ? null : deps.agentApi.findKeyByHash(hashAgentApiKey(token));
+ if (key === null) throw unauthorized("Invalid API key.");
+ if (key.projectId !== api.projectId || key.agentId !== api.agentId) throw notTheKeys();
+ return key.keyId;
+ };
+
+ return async (c, next) => {
+ requireAgentApiOn(deps.settings);
+ const segments = segmentsOf(c.req.path, prefix);
+ const header = c.req.header("authorization");
+ if (segments !== null && segments[0] === "agents" && segments.length >= 3) {
+ const [, projectId, agentId] = segments as [string, string, string];
+ const api = await requireExposedAgent(deps, projectId, agentId);
+ const keyId = authenticate(header, api, agentNotFound);
+ c.set("amsp", { projectId, agentId, keyId, session: null });
+ } else if (segments !== null && segments[0] === "sessions" && segments.length >= 2) {
+ const sessionId = segments[1]!;
+ if (!isValidId(sessionId)) throw sessionNotFound();
+ const row = deps.sessions.findById(sessionId);
+ if (row === null || row.client !== "api") throw sessionNotFound();
+ const api = deps.agentApi.get(row.projectId, row.agentId);
+ if (api === null || !api.enabled) throw sessionNotFound();
+ const keyId = authenticate(header, api, sessionNotFound);
+ c.set("amsp", { projectId: row.projectId, agentId: row.agentId, keyId, session: row });
+ }
+ await next();
+ };
+}
diff --git a/packages/server/src/amsp/keys.ts b/packages/server/src/amsp/keys.ts
new file mode 100644
index 00000000..ff0356ea
--- /dev/null
+++ b/packages/server/src/amsp/keys.ts
@@ -0,0 +1,33 @@
+/**
+ * Agent API keys: `penguin_` + 43 base64url characters (32 random bytes), shown once at creation.
+ * Only the sha256 of a key is stored, so authenticating a request is a lookup of a fixed-length
+ * digest — its timing does not depend on how much of a guess matches a real key.
+ */
+import { createHash, randomBytes } from "node:crypto";
+
+/** The marker every key starts with, so a leaked one is recognizable for what it is. */
+export const AGENT_API_KEY_PREFIX = "penguin_";
+
+/** How many leading characters of a key the list shows (`penguin_` + 8). */
+const SHOWN_PREFIX_LENGTH = 16;
+
+/** sha256 of a presented key, hex: what `agent_api_keys.token_hash` holds. */
+export function hashAgentApiKey(secret: string): string {
+ return createHash("sha256").update(secret, "utf8").digest("hex");
+}
+
+/** A fresh key: the secret (handed to the caller once), its hash and the prefix the list shows. */
+export function mintAgentApiKey(): {
+ keyId: string;
+ secret: string;
+ tokenHash: string;
+ prefix: string;
+} {
+ const secret = AGENT_API_KEY_PREFIX + randomBytes(32).toString("base64url");
+ return {
+ keyId: randomBytes(12).toString("base64url"),
+ secret,
+ tokenHash: hashAgentApiKey(secret),
+ prefix: secret.slice(0, SHOWN_PREFIX_LENGTH),
+ };
+}
diff --git a/packages/server/src/amsp/module.ts b/packages/server/src/amsp/module.ts
new file mode 100644
index 00000000..d376c9a5
--- /dev/null
+++ b/packages/server/src/amsp/module.ts
@@ -0,0 +1,86 @@
+/**
+ * The Agent API's place in the platform tree: one group holding the per-Agent settings and keys
+ * (AgentApiRepo, exported as the AgentApi mechanism for the Agent list, the API tab's routes and
+ * the deletion cascades) and the public AMSP routes.
+ *
+ * The public group is contributed `auth: "none"` at order 5, with `/api/auth`, `/api/desktop`
+ * and `/api/hmr`: ahead of the `/api/*` cookie gate, which `HttpModule` installs in front of the
+ * first `auth: "user"` group (order 10 and up). The API tab's own routes are an ordinary
+ * signed-in group, mounted beside the other Agent sub-groups (services/agent-routes.ts); its Try
+ * it route is contributed here instead, as a second, signed-in group (try-route.ts), since it
+ * runs the public group's handler with the same dependencies. Its order, one below the tab's
+ * group, only fixes the mount order: that group has no catch-all to shadow it.
+ */
+import { Bind, Component, Module, Use } from "@lmliheng/penguin-core/kernel";
+import type { Hono } from "hono";
+import type { AppEnv } from "../auth/middleware.js";
+import { AgentApiRepo } from "../db/repos/agent-api.js";
+import type { Channels, Clock, Log } from "../hmr/capabilities.js";
+import { AgentApi } from "../mechanisms/agent-api.js";
+import type { AgentConfig } from "../mechanisms/agents.js";
+import type { Access } from "../mechanisms/projects.js";
+import type { Errors } from "../mechanisms/observability.js";
+import type { SessionIndex } from "../mechanisms/sessions.js";
+import type { Settings } from "../mechanisms/settings.js";
+import type { SessionManager, Sessions, SessionServiceIface } from "../runtime/session-manager.js";
+import type { SessionService } from "../services/session-service.js";
+import { amspRoutes } from "./routes.js";
+import { agentApiTryRoutes } from "./try-route.js";
+
+/**
+ * The public `/api/amsp/v1` group: the gate, CORS, the run stream and the Session routes; and
+ * the API tab's Try it, the same run for the owner's sign-in.
+ */
+@Component({
+ contributes: {
+ "HttpModule.routes": [
+ { id: "AmspRoutes.routes", prefix: "/api/amsp/v1", auth: "none", order: 5 },
+ {
+ id: "AmspRoutes.try",
+ prefix: "/api/projects/:projectId/agents/:agentId/api/try",
+ auth: "user",
+ order: 224,
+ },
+ ],
+ },
+})
+export class AmspRoutes {
+ @Use() private readonly settings!: Settings;
+ @Use() private readonly agentApi!: AgentApi;
+ @Use() private readonly sessions!: SessionIndex;
+ @Use() private readonly manager!: Sessions;
+ @Use() private readonly sessionService!: SessionServiceIface;
+ @Use() private readonly channels!: Channels;
+ @Use() private readonly agentConfig!: AgentConfig;
+ @Use() private readonly log!: Log;
+ @Use() private readonly errors!: Errors;
+ @Use() private readonly clock!: Clock;
+ @Use() private readonly access!: Access;
+ @Bind("AmspRoutes.routes") routes!: Hono<AppEnv>;
+ @Bind("AmspRoutes.try") tryRoutes!: Hono<AppEnv>;
+
+ setup() {
+ const clock = this.clock;
+ const deps = {
+ settings: this.settings,
+ agentApi: this.agentApi,
+ sessions: this.sessions,
+ manager: this.manager as SessionManager,
+ sessionService: this.sessionService as SessionService,
+ channels: this.channels,
+ agentConfig: this.agentConfig,
+ log: this.log,
+ errors: this.errors,
+ now: () => clock.now(),
+ };
+ this.routes = amspRoutes(deps);
+ this.tryRoutes = agentApiTryRoutes({ ...deps, access: this.access });
+ }
+}
+
+/** The Agent API: per-Agent settings and keys in web.db, and the public AMSP routes. */
+@Module({
+ children: [AgentApiRepo, AmspRoutes],
+ exports: [AgentApi],
+})
+export class AgentApiModule {}
diff --git a/packages/server/src/amsp/routes.ts b/packages/server/src/amsp/routes.ts
new file mode 100644
index 00000000..af1d98ae
--- /dev/null
+++ b/packages/server/src/amsp/routes.ts
@@ -0,0 +1,112 @@
+/**
+ * The Agent API's public routes, `/api/amsp/v1` — mounted in front of the cookie gate, since an
+ * external program has no cookie: the key, when there is one, is all it presents.
+ *
+ * GET /agents/:projectId/:agentId the Agent's name and description
+ * POST /agents/:projectId/:agentId/runs one run, streamed (run-stream.ts)
+ * GET /sessions/:sessionId an API Session's state and model
+ * POST /sessions/:sessionId/abort 202 interrupted / 204 nothing running
+ * POST /sessions/:sessionId/approvals/:toolCallId answer a pending approval
+ * * anything else 404 not_found (JSON, never the SPA)
+ *
+ * CORS (cors.ts): a preflight is always answered; `Access-Control-Allow-Origin: *` goes only on
+ * requests that carry `Authorization`, the global 413/415 refusals included. The `/api/*` CSRF
+ * guard (JSON-only writes) stays in force; nothing here reads a cookie.
+ *
+ * One route of the family sits behind the cookie gate instead: the API tab's Try it,
+ * `POST /api/projects/:projectId/agents/:agentId/api/try` (try-route.ts), the runs route's
+ * handler for the Project owner's sign-in in place of a key.
+ */
+import { Hono } from "hono";
+import type { AgentResponse, SessionResponse } from "@lmliheng/amsp";
+import type { AppEnv } from "../auth/middleware.js";
+import { HttpError } from "../http/errors.js";
+import { readJson, requireEnum } from "../http/validate.js";
+import type { AgentConfig } from "../mechanisms/agents.js";
+import type { Settings } from "../mechanisms/settings.js";
+import { AMSP_PREFIX, amspCors } from "./cors.js";
+import { amspGate } from "./gate.js";
+import type { AmspEnv, AmspGateDeps } from "./gate.js";
+import { runStream } from "./run-stream.js";
+import type { RunStreamDeps } from "./run-stream.js";
+
+export interface AmspRouteDeps
+ extends
+ Omit<AmspGateDeps, "settings" | "agentConfig">,
+ Omit<RunStreamDeps, "settings" | "manager"> {
+ settings: Pick<Settings, "getAgentApiEnabled" | "getAttachmentLimitsMb">;
+ agentConfig: Pick<AgentConfig, "exists" | "readCardMeta">;
+ manager: RunStreamDeps["manager"] & {
+ decideApproval(sessionId: string, toolCallId: string, decision: "allow" | "deny"): boolean;
+ };
+}
+
+export function amspRoutes(deps: AmspRouteDeps): Hono<AppEnv> {
+ const app = new Hono<AmspEnv>();
+
+ app.use("*", amspCors);
+
+ app.use("*", amspGate(AMSP_PREFIX, deps));
+
+ app.get("/agents/:projectId/:agentId", async (c) => {
+ const { projectId, agentId } = c.var.amsp;
+ const meta = await deps.agentConfig.readCardMeta(projectId, agentId);
+ const body: AgentResponse = {
+ agent: {
+ id: `${projectId}/${agentId}`,
+ ...(meta.name !== undefined ? { name: meta.name } : {}),
+ ...(meta.description !== undefined ? { description: meta.description } : {}),
+ },
+ };
+ return c.json(body);
+ });
+
+ app.post("/agents/:projectId/:agentId/runs", (c) => runStream(c, deps));
+
+ app.get("/sessions/:sessionId", (c) => {
+ const { projectId, agentId, session } = c.var.amsp;
+ const row = session!;
+ const body: SessionResponse = {
+ session: {
+ id: row.sessionId,
+ agent: `${projectId}/${agentId}`,
+ status: deps.manager.statusOf(row.sessionId),
+ provider: row.provider,
+ model_id: row.modelId,
+ created_at: row.createdAt,
+ last_active_at: row.lastActiveAt,
+ },
+ };
+ return c.json(body);
+ });
+
+ app.post("/sessions/:sessionId/abort", (c) => {
+ const sessionId = c.var.amsp.session!.sessionId;
+ // Pending approvals are denied first, then the run is signalled; the run's own stream stays
+ // open until it ends with run.done "aborted".
+ return c.body(null, deps.manager.abortTask(sessionId) ? 202 : 204);
+ });
+
+ app.post("/sessions/:sessionId/approvals/:toolCallId", async (c) => {
+ const sessionId = c.var.amsp.session!.sessionId;
+ const toolCallId = c.req.param("toolCallId");
+ const body = await readJson(c);
+ const decision = requireEnum(body, "decision", ["allow", "deny"] as const);
+ // The same registry the Web App's approval card answers: whichever answer comes first wins.
+ if (!deps.manager.decideApproval(sessionId, toolCallId, decision)) {
+ throw new HttpError(
+ 404,
+ "approval_not_found",
+ "No pending approval for this tool call (already decided, or unknown).",
+ );
+ }
+ return c.body(null, 204);
+ });
+
+ // The group owns its prefix: an unknown path is a JSON 404, never the SPA or the cookie gate's 401.
+ app.all("/*", () => {
+ throw new HttpError(404, "not_found", "Not found.");
+ });
+
+ return app as unknown as Hono<AppEnv>;
+}
diff --git a/packages/server/src/amsp/run-stream.ts b/packages/server/src/amsp/run-stream.ts
new file mode 100644
index 00000000..046944a5
--- /dev/null
+++ b/packages/server/src/amsp/run-stream.ts
@@ -0,0 +1,346 @@
+/**
+ * The run handler: `POST /api/amsp/v1/agents/:projectId/:agentId/runs` is the run and its
+ * stream.
+ *
+ * 1. The gate (gate.ts) has resolved the Agent and the key before anything here runs.
+ * 2. The body is read and validated: `input` (a string, or text / image_url items) becomes the
+ * run's input messages — texts first, then images, as the composer submits them.
+ * 3. The Session: without `session_id` a new one is created — source `api`, client `api`, the
+ * Agent's API approval mode copied onto its row, the model and sandbox the server's new-chat
+ * defaults; with one, it must be an API Session of this Agent. An Agent already running
+ * AMSP_MAX_CONCURRENT_RUNS Sessions is refused 429 before a run would add one more.
+ * 4. The handler subscribes to the Session's channel BEFORE the Task starts, so nothing of the
+ * run can be published unseen; a busy Session is refused (409) by `startTask` itself, with
+ * nothing streamed.
+ * 5. The stream: `run.started`, then every channel event through the translator, a
+ * `: keep-alive` comment after KEEPALIVE_MS of silence, and `run.done` — always the last
+ * event, a server failure included — followed by `data: [DONE]`.
+ *
+ * Disconnecting aborts the run: a run nobody is reading would only spend the Project's tokens,
+ * and an approval asked of a caller that went away would never be answered. A server failure
+ * that ends the stream aborts it for the same reason.
+ */
+import { imageUrlMessage, isValidId, userText } from "@lmliheng/penguin-core";
+import type { OmniMessage } from "@lmliheng/penguin-core";
+import type { AmspEvent, RunStarted } from "@lmliheng/amsp";
+import type { Context } from "hono";
+import { streamSSE } from "hono/streaming";
+import type { ApprovalMode } from "../api/types.js";
+import type { Channels, Log } from "../hmr/capabilities.js";
+import { HttpError } from "../http/errors.js";
+import { badRequest, readJson } from "../http/validate.js";
+import type { AgentApi } from "../mechanisms/agent-api.js";
+import type { Errors } from "../mechanisms/observability.js";
+import type { SessionIndex } from "../mechanisms/sessions.js";
+import type { Settings } from "../mechanisms/settings.js";
+import type { ChannelEvent } from "../runtime/channel.js";
+import type { SessionManager } from "../runtime/session-manager.js";
+import type { SessionService } from "../services/session-service.js";
+import {
+ INLINE_IMAGE_MAX_BYTES,
+ INLINE_IMAGE_MAX_MB,
+ toAttachmentLimits,
+} from "../services/attachment-limits.js";
+import { sessionNotFound } from "./gate.js";
+import type { AmspEnv } from "./gate.js";
+import { AmspTranslator } from "./translate.js";
+
+/** Silence after which a `: keep-alive` comment is written (MMSP's value). */
+export const KEEPALIVE_MS = 15_000;
+
+/** How many Sessions of one Agent may run at once through any door before the API refuses another. */
+export const AMSP_MAX_CONCURRENT_RUNS = 4;
+
+/** What the run handler reaches: the seams the messaging bridge and the web routes use. */
+export interface RunStreamDeps {
+ manager: Pick<SessionManager, "startTask" | "abortTask" | "statusOf" | "activeCountForAgent">;
+ sessionService: Pick<SessionService, "createSession">;
+ sessions: Pick<SessionIndex, "findById">;
+ agentApi: AgentApi;
+ settings: Pick<Settings, "getAttachmentLimitsMb">;
+ channels: Pick<Channels, "get">;
+ errors: Errors;
+ log: Log;
+ now: () => Date;
+}
+
+/**
+ * A base64 `data:` URL of an image: an `image/*` MIME, the `;base64,` marker, a non-empty body.
+ * The same shape the tasks route admits, narrowed to images: the API takes no files in v1.
+ */
+const IMAGE_DATA_URL = /^data:image\/[A-Za-z0-9.+-]+;base64,[A-Za-z0-9+/=\s]+$/;
+
+/** Decoded size of a base64 data URL, from its length (padding and whitespace carry no bytes). */
+function dataUrlBytes(url: string): number {
+ const payload = url.slice(url.indexOf(",") + 1).replace(/[=\s]+/g, "");
+ return Math.floor((payload.length * 3) / 4);
+}
+
+/**
+ * `input` as the run's messages: a string is one user text; items are texts and images, texts
+ * first. At least one non-empty text or one image. A `data:` image must be an image MIME within
+ * the inline-image cap, and all of them together within the admin's per-message total; an
+ * http(s) URL is passed on untouched (the server does not fetch it).
+ */
+export function parseRunInput(input: unknown, totalImageBytes: number): OmniMessage[] {
+ const empty = () =>
+ badRequest("input must be a non-empty string, or an array of text and image_url items.");
+ if (typeof input === "string") {
+ if (input.trim() === "") throw empty();
+ return [userText(input)];
+ }
+ if (!Array.isArray(input) || input.length === 0) throw empty();
+ const texts: OmniMessage[] = [];
+ const images: OmniMessage[] = [];
+ let imageBytes = 0;
+ input.forEach((item: unknown, i) => {
+ if (item === null || typeof item !== "object" || Array.isArray(item)) {
+ throw badRequest(`input[${i}] must be an object.`);
+ }
+ const part = item as Record<string, unknown>;
+ if (part.type === "text") {
+ if (typeof part.text !== "string" || part.text.trim() === "") {
+ throw badRequest(`input[${i}].text must be a non-empty string.`);
+ }
+ texts.push(userText(part.text));
+ return;
+ }
+ if (part.type === "image_url") {
+ const url = part.image_url;
+ if (typeof url === "string" && (url.startsWith("http://") || url.startsWith("https://"))) {
+ images.push(imageUrlMessage(url));
+ return;
+ }
+ if (typeof url !== "string" || !url.startsWith("data:image/")) {
+ throw badRequest(
+ `input[${i}].image_url must be an http(s) URL or a base64 data URL of an image (data:image/<type>;base64,<bytes>).`,
+ );
+ }
+ // Sized before it is pattern-checked: an oversized body is refused without a scan.
+ const bytes = dataUrlBytes(url);
+ if (bytes > INLINE_IMAGE_MAX_BYTES) {
+ throw badRequest(
+ `input[${i}].image_url exceeds the ${INLINE_IMAGE_MAX_MB}MB inline image limit.`,
+ );
+ }
+ if (!IMAGE_DATA_URL.test(url)) {
+ throw badRequest(
+ `input[${i}].image_url must be an http(s) URL or a base64 data URL of an image (data:image/<type>;base64,<bytes>).`,
+ );
+ }
+ imageBytes += bytes;
+ images.push(imageUrlMessage(url));
+ return;
+ }
+ if (part.type === "file") {
+ throw badRequest(`input[${i}]: the Agent API takes no files; send text and image_url items.`);
+ }
+ throw badRequest(`input[${i}].type must be text or image_url.`);
+ });
+ if (imageBytes > totalImageBytes) {
+ throw badRequest(
+ `input's images exceed the ${Math.floor(totalImageBytes / (1024 * 1024))}MB per-message limit.`,
+ );
+ }
+ return [...texts, ...images];
+}
+
+/** A FIFO the channel listener fills and the stream loop drains; `next` answers null once closed. */
+class Inbox<T> {
+ private items: T[] = [];
+ private waiter: ((item: T | null) => void) | null = null;
+ private closed = false;
+
+ push(item: T): void {
+ if (this.closed) return;
+ const waiter = this.waiter;
+ if (waiter !== null) {
+ this.waiter = null;
+ waiter(item);
+ } else {
+ this.items.push(item);
+ }
+ }
+
+ next(): Promise<T | null> {
+ if (this.items.length > 0) return Promise.resolve(this.items.shift()!);
+ if (this.closed) return Promise.resolve(null);
+ return new Promise((resolve) => {
+ this.waiter = resolve;
+ });
+ }
+
+ /** Stops the loop: what is still queued is dropped, and a pending `next` answers null. */
+ close(): void {
+ this.closed = true;
+ this.items = [];
+ const waiter = this.waiter;
+ this.waiter = null;
+ waiter?.(null);
+ }
+}
+
+const tooManyRuns = (): HttpError =>
+ new HttpError(
+ 429,
+ "too_many_runs",
+ `This Agent already has ${AMSP_MAX_CONCURRENT_RUNS} conversations running; try again shortly.`,
+ 2,
+ );
+
+const KEEPALIVE = Symbol("keep-alive");
+
+export async function runStream(c: Context<AmspEnv>, deps: RunStreamDeps): Promise<Response> {
+ const { projectId, agentId, keyId } = c.var.amsp;
+ const agent = `${projectId}/${agentId}`;
+ const body = await readJson(c);
+ const sessionField = body.session_id;
+ if (
+ sessionField !== undefined &&
+ (typeof sessionField !== "string" || !isValidId(sessionField))
+ ) {
+ throw badRequest("session_id must be a Session id.");
+ }
+ const input = parseRunInput(
+ body.input,
+ toAttachmentLimits(deps.settings.getAttachmentLimitsMb()).totalBytes,
+ );
+ const full = () =>
+ deps.manager.activeCountForAgent(projectId, agentId) >= AMSP_MAX_CONCURRENT_RUNS;
+
+ let sessionId: string;
+ if (sessionField !== undefined) {
+ const row = deps.sessions.findById(sessionField);
+ if (
+ row === null ||
+ row.client !== "api" ||
+ row.projectId !== projectId ||
+ row.agentId !== agentId
+ ) {
+ throw sessionNotFound();
+ }
+ sessionId = row.sessionId;
+ // A Session that is itself running is refused 409 by startTask below; an idle one would add a
+ // run to the Agent.
+ if (deps.manager.statusOf(sessionId) === "idle" && full()) throw tooManyRuns();
+ } else {
+ if (full()) throw tooManyRuns();
+ const approvalMode: ApprovalMode =
+ deps.agentApi.get(projectId, agentId)?.approvalMode ?? "allow-all";
+ const created = await deps.sessionService.createSession({
+ projectId,
+ agentId,
+ source: "api",
+ client: "api",
+ approvalMode,
+ });
+ sessionId = created.sessionId;
+ }
+ if (keyId !== null) deps.agentApi.touchKey(keyId, deps.now().toISOString());
+
+ const inbox = new Inbox<ChannelEvent | typeof KEEPALIVE>();
+ const translator = new AmspTranslator(input, { now: deps.now });
+ let unsubscribe = deps.channels.get(sessionId).subscribe((evt) => inbox.push(evt));
+ let actual: string;
+ try {
+ ({ sessionId: actual } = await deps.manager.startTask(sessionId, input));
+ } catch (err) {
+ unsubscribe();
+ throw err;
+ }
+ // A Session whose Trace was gone heals into a new id at load: its channel is a fresh one that
+ // received the input before this handler could subscribe. Follow it, unless the run already
+ // ended there unseen.
+ let rebuilt = false;
+ if (actual !== sessionId) {
+ unsubscribe();
+ unsubscribe = deps.channels.get(actual).subscribe((evt) => inbox.push(evt));
+ translator.begin();
+ rebuilt = deps.manager.statusOf(actual) === "idle";
+ }
+
+ const response = streamSSE(c, async (stream) => {
+ let ended = false;
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ const arm = (): void => {
+ if (timer !== null) clearTimeout(timer);
+ timer = setTimeout(() => inbox.push(KEEPALIVE), KEEPALIVE_MS);
+ };
+ const write = async (event: AmspEvent): Promise<void> => {
+ await stream.writeSSE({ data: JSON.stringify(event) });
+ arm();
+ };
+ const end = async (event: AmspEvent): Promise<void> => {
+ ended = true;
+ await write(event);
+ await stream.writeSSE({ data: "[DONE]" });
+ };
+ stream.onAbort(() => {
+ if (!ended) deps.manager.abortTask(actual);
+ inbox.close();
+ });
+ try {
+ const started: RunStarted = {
+ type: "run.started",
+ at: deps.now().toISOString(),
+ session_id: actual,
+ agent,
+ };
+ await write(started);
+ if (rebuilt) {
+ await end(
+ translator.fail({
+ code: "session_rebuilt",
+ message: `The Session was rebuilt as ${actual} and its run could not be followed.`,
+ }),
+ );
+ return;
+ }
+ for (;;) {
+ const item = await inbox.next();
+ if (item === null) return;
+ if (item === KEEPALIVE) {
+ await stream.write(": keep-alive\n\n");
+ arm();
+ continue;
+ }
+ for (const event of translator.feed(item)) {
+ if (event.type === "run.done") {
+ await end(event);
+ return;
+ }
+ await write(event);
+ }
+ }
+ } catch (err) {
+ // A write the caller's departure broke is the disconnect, already handled by onAbort.
+ if (stream.aborted) return;
+ const message = err instanceof Error ? err.message : String(err);
+ deps.log.line(`[amsp] run stream of ${actual} failed: ${message}`);
+ deps.errors.record({
+ source: "session",
+ err,
+ ctx: { projectId, agentId, sessionId: actual },
+ code: "amsp_stream_failed",
+ kind: "unexpected",
+ });
+ if (!ended) {
+ // Nobody follows the run any more: stop it, as a disconnect would.
+ deps.manager.abortTask(actual);
+ try {
+ await end(translator.fail({ code: "internal", message }));
+ } catch {
+ // Best effort: the connection may be gone as well.
+ }
+ }
+ } finally {
+ if (timer !== null) clearTimeout(timer);
+ unsubscribe();
+ inbox.close();
+ }
+ });
+ // streamSSE names the bare type; the stream is UTF-8 JSON, and says so.
+ response.headers.set("Content-Type", "text/event-stream; charset=utf-8");
+ response.headers.set("X-Accel-Buffering", "no");
+ return response;
+}
diff --git a/packages/server/src/amsp/translate.ts b/packages/server/src/amsp/translate.ts
new file mode 100644
index 00000000..87451613
--- /dev/null
+++ b/packages/server/src/amsp/translate.ts
@@ -0,0 +1,508 @@
+/**
+ * AmspTranslator: the Session's live stream, projected onto AMSP.
+ *
+ * What a run handler subscribes to is the Session's channel (runtime/channel.ts): OmniMessage
+ * envelopes as the engine yields them, and the server's own events (`server_event`). This class
+ * turns one channel event at a time into the AMSP events it stands for — usually one, often none —
+ * and ends the run with exactly one `run.done` when the Session goes idle. It is pure: no I/O, a
+ * clock passed in, nothing read but what it is fed.
+ *
+ * The rules it keeps (the protocol reference spells them out):
+ * - Fragments and complete items are forwarded as they are, never reconciled: `partial_*`
+ * start/delta become `K.delta`, a `stop` fragment becomes nothing, and the complete message
+ * becomes `K.done`. No `.done` is built from fragments; a tool call's `arguments` stay the raw
+ * JSON string.
+ * - The run's own input — the envelopes the run handler submitted, which the manager publishes at
+ * launch — is dropped, and nothing on the channel counts before it: whatever the Session
+ * published earlier (an idle `task_state` a child's state change re-published, a background
+ * child's output) is not this run's.
+ * - Request ordinals, held usage and the compaction flag are kept per origin: a child Session
+ * counts its own requests and never disturbs the main Session's.
+ * - Usage: a `token_usage` precedes its `request_end` and is stamped on that `request.done`, or,
+ * inside a compaction, summed onto its `compaction.done`. `run.done.usage` sums every stamped
+ * usage of the run, children's included; `session_usage` is the main Session's cumulative count
+ * as the engine last reported it.
+ * - Inside a compaction the summary rides as `summary.*`; the compaction request's thinking is
+ * not forwarded (only `summary.*` items sit between `compaction.started` and
+ * `compaction.done`).
+ * - `run.done.status`: the main Session's `abort` wins (`aborted`, its error code); else its last
+ * unrecovered terminal record — a non-completed `request_end` with no planned retry, or a
+ * non-completed `compaction_end` no later request followed — with that record's error; else
+ * `fatal` without an error when the main Session's last assistant text ended `fatal` (the
+ * engine's max-turns notice); else `completed`.
+ */
+import type {
+ AbortPayload,
+ ApprovalDecisionPayload,
+ CompactionBeginPayload,
+ CompactionEndPayload,
+ ErrorInfo,
+ HookPayload,
+ ImageUrlPayload,
+ InlineDataPayload,
+ InlineThinkingPayload,
+ McpConnectBeginPayload,
+ McpConnectEndPayload,
+ OmniMessage,
+ PartialTextPayload,
+ PartialThinkingPayload,
+ PartialToolCallOutputPayload,
+ PartialToolCallPayload,
+ RequestEndPayload,
+ SessionMetaPayload,
+ TextPayload,
+ ThinkingPayload,
+ TokenCounts as OmniTokenCounts,
+ TokenUsagePayload,
+ ToolCallOutputPayload,
+ ToolCallPayload,
+ ToolListReadyPayload,
+} from "@lmliheng/penguin-core";
+import type { AmspError, AmspEvent, RunDone, StopReason, TokenCounts } from "@lmliheng/amsp";
+import type { ServerEvent } from "../api/types.js";
+import type { ChannelEvent } from "../runtime/channel.js";
+
+/** The terminal record a run's status is read from (main Session only). */
+interface Terminal {
+ status: StopReason;
+ error?: AmspError;
+}
+
+/** `{ at, origin? }`, the head every AMSP event carries. */
+type Head = { at: string; origin?: string[] };
+
+const zero = (): TokenCounts => ({ cache_read: 0, cache_write: 0, output: 0, total: 0 });
+
+function counts(c: OmniTokenCounts): TokenCounts {
+ return { cache_read: c.cache_read, cache_write: c.cache_write, output: c.output, total: c.total };
+}
+
+function add(a: TokenCounts, b: TokenCounts): TokenCounts {
+ return {
+ cache_read: a.cache_read + b.cache_read,
+ cache_write: a.cache_write + b.cache_write,
+ output: a.output + b.output,
+ total: a.total + b.total,
+ };
+}
+
+/** The record's error pair as AMSP's one error shape; absent when the record names no cause. */
+function errorOf(p: ErrorInfo): AmspError | undefined {
+ if (p.error_code === undefined && p.error_message === undefined) return undefined;
+ return { code: p.error_code ?? "unknown", message: p.error_message ?? "" };
+}
+
+/** `error` as an optional property: spread into an event so an absent error leaves no key. */
+function errorProp(error: AmspError | undefined): { error?: AmspError } {
+ return error === undefined ? {} : { error };
+}
+
+export interface AmspTranslatorOptions {
+ /** The clock server-originated events (`run.done`, `approval.requested`) are stamped with. */
+ now?: () => Date;
+}
+
+export class AmspTranslator {
+ private readonly now: () => Date;
+ /** The submitted input envelopes, serialized: each is dropped once when its echo arrives. */
+ private readonly echoes: string[];
+ /** Whether this run's input has been seen on the channel: nothing before it is this run's. */
+ private started = false;
+ private finished = false;
+ /** Per origin (joined chain; "" = the main Session): the current request ordinal. */
+ private readonly ordinals = new Map<string, number>();
+ /** Per origin: the `token_usage` waiting for its `request_end`. */
+ private readonly heldUsage = new Map<string, TokenCounts>();
+ /** Per origin inside a compaction: the usage its attempts have reported so far. */
+ private readonly compactions = new Map<string, TokenCounts | null>();
+ private requests = 0;
+ private usage: TokenCounts = zero();
+ private sessionUsage: TokenCounts | null = null;
+ private abort: AmspError | null = null;
+ private terminal: Terminal | null = null;
+ /** stop_reason of the main Session's last assistant `text` (the max-turns notice ends `fatal`). */
+ private lastMainText: StopReason | null = null;
+
+ /**
+ * `input` is exactly what the run handler hands `startTask`: the manager publishes those
+ * envelopes at launch, and their serialized form is how their echo is recognized.
+ */
+ constructor(input: readonly OmniMessage[], opts: AmspTranslatorOptions = {}) {
+ this.now = opts.now ?? (() => new Date());
+ this.echoes = input.map((m) => JSON.stringify(m));
+ }
+
+ /** Whether `run.done` has been produced; nothing is translated after it. */
+ get done(): boolean {
+ return this.finished;
+ }
+
+ /**
+ * Opens the run without waiting for the input's echo: for a handler that followed the Session
+ * to a new id (a Trace-less self-heal), whose channel received the input before the handler
+ * could subscribe to it.
+ */
+ begin(): void {
+ this.started = true;
+ }
+
+ /** One channel event in, the AMSP events it stands for out (possibly none). */
+ feed(evt: ChannelEvent): AmspEvent[] {
+ if (this.finished) return [];
+ if (evt.event === "server_event") {
+ return this.started ? this.serverEvent(JSON.parse(evt.data) as ServerEvent) : [];
+ }
+ if (evt.event !== undefined) return [];
+ const echo = this.echoes.indexOf(evt.data);
+ if (echo >= 0) {
+ this.echoes.splice(echo, 1);
+ this.started = true;
+ return [];
+ }
+ if (!this.started) return [];
+ return this.message(JSON.parse(evt.data) as OmniMessage);
+ }
+
+ /**
+ * Ends the run on a failure of the server's own (the handler could not go on driving it): a
+ * `run.done` `fatal` carrying `error`, with the usage counted so far.
+ */
+ fail(error: AmspError): RunDone {
+ this.finished = true;
+ return this.runDone("fatal", error);
+ }
+
+ private serverEvent(event: ServerEvent): AmspEvent[] {
+ if (event.type === "task_state") {
+ // `running` is re-published mid-run (queue, steering, children's state): only idle ends it.
+ return event.state === "idle" ? [this.finish()] : [];
+ }
+ if (event.type === "approval_request") {
+ const call = event.toolCall.payload;
+ return [
+ {
+ type: "approval.requested",
+ at: this.now().toISOString(),
+ ...(event.origin !== undefined && event.origin.length > 0
+ ? { origin: [...event.origin] }
+ : {}),
+ tool_call: {
+ tool_call_id: call.tool_call_id,
+ name: call.name,
+ arguments: call.arguments,
+ },
+ },
+ ];
+ }
+ return [];
+ }
+
+ private finish(): RunDone {
+ this.finished = true;
+ if (this.abort !== null) return this.runDone("aborted", this.abort);
+ if (this.terminal !== null) return this.runDone(this.terminal.status, this.terminal.error);
+ if (this.lastMainText === "fatal") return this.runDone("fatal");
+ return this.runDone("completed");
+ }
+
+ private runDone(status: StopReason, error?: AmspError): RunDone {
+ return {
+ type: "run.done",
+ at: this.now().toISOString(),
+ status,
+ ...errorProp(error),
+ requests: this.requests,
+ usage: { ...this.usage },
+ session_usage: this.sessionUsage === null ? null : { ...this.sessionUsage },
+ };
+ }
+
+ private message(msg: OmniMessage): AmspEvent[] {
+ const origin = msg.origin !== undefined && msg.origin.length > 0 ? [...msg.origin] : undefined;
+ const key = origin === undefined ? "" : origin.join("/");
+ const main = origin === undefined;
+ const head: Head = { at: msg.timestamp, ...(origin !== undefined ? { origin } : {}) };
+ const compacting = this.compactions.has(key);
+
+ if (msg.type === "session_meta") {
+ const p = msg.payload as SessionMetaPayload;
+ const contextWindow = p.model_context_window;
+ return [
+ {
+ type: "context.opened",
+ ...head,
+ session_id: p.session_id,
+ provider: p.provider,
+ model_id: p.model_id,
+ context_window: typeof contextWindow === "number" ? contextWindow : "unknown",
+ },
+ ];
+ }
+
+ const kind = (msg.payload as { type: string }).type;
+ switch (kind) {
+ case "partial_text": {
+ const p = msg.payload as PartialTextPayload;
+ if (p.event_type === "stop") return [];
+ return compacting
+ ? [{ type: "summary.delta", ...head, text: p.text }]
+ : [{ type: "text.delta", ...head, role: "assistant", text: p.text }];
+ }
+ case "text": {
+ const p = msg.payload as TextPayload;
+ const stop = p.stop_reason ?? "completed";
+ if (p.role === "user") {
+ return [
+ {
+ type: "text.done",
+ ...head,
+ role: "user",
+ text: p.text,
+ stop_reason: stop,
+ ...(p.sender !== undefined ? { sender: p.sender } : {}),
+ },
+ ];
+ }
+ if (compacting) return [{ type: "summary.done", ...head, text: p.text, stop_reason: stop }];
+ if (main) this.lastMainText = stop;
+ return [{ type: "text.done", ...head, role: "assistant", text: p.text, stop_reason: stop }];
+ }
+ case "partial_thinking": {
+ const p = msg.payload as PartialThinkingPayload;
+ if (p.event_type === "stop" || compacting) return [];
+ return [{ type: "thinking.delta", ...head, thinking: p.thinking }];
+ }
+ case "thinking": {
+ const p = msg.payload as ThinkingPayload;
+ if (compacting) return [];
+ return [
+ {
+ type: "thinking.done",
+ ...head,
+ thinking: p.thinking,
+ stop_reason: p.stop_reason ?? "completed",
+ },
+ ];
+ }
+ case "partial_tool_call": {
+ const p = msg.payload as PartialToolCallPayload;
+ if (p.event_type === "stop") return [];
+ return [
+ {
+ type: "tool_call.delta",
+ ...head,
+ tool_call_id: p.tool_call_id,
+ name: p.name,
+ arguments: p.arguments,
+ },
+ ];
+ }
+ case "tool_call": {
+ const p = msg.payload as ToolCallPayload;
+ return [
+ {
+ type: "tool_call.done",
+ ...head,
+ tool_call_id: p.tool_call_id,
+ name: p.name,
+ arguments: p.arguments,
+ stop_reason: p.stop_reason ?? "completed",
+ },
+ ];
+ }
+ case "partial_tool_call_output": {
+ const p = msg.payload as PartialToolCallOutputPayload;
+ if (p.event_type === "stop") return [];
+ return [
+ {
+ type: "tool_result.delta",
+ ...head,
+ tool_call_id: p.tool_call_id,
+ output: p.output ?? "",
+ ...(p.images !== undefined ? { images: [...p.images] } : {}),
+ },
+ ];
+ }
+ case "tool_call_output": {
+ const p = msg.payload as ToolCallOutputPayload;
+ return [
+ {
+ type: "tool_result.done",
+ ...head,
+ tool_call_id: p.tool_call_id,
+ output: p.output,
+ ...(p.images !== undefined ? { images: [...p.images] } : {}),
+ stop_reason: p.stop_reason ?? "completed",
+ },
+ ];
+ }
+ case "image_url": {
+ const p = msg.payload as ImageUrlPayload;
+ return [{ type: "image_url.done", ...head, role: "user", image_url: p.image_url }];
+ }
+ case "inline_data": {
+ const p = msg.payload as InlineDataPayload;
+ return [
+ {
+ type: "inline_data.done",
+ ...head,
+ role: p.role,
+ mime_type: p.mime_type,
+ data: p.data,
+ stop_reason: p.stop_reason ?? "completed",
+ },
+ ];
+ }
+ case "inline_thinking": {
+ const p = msg.payload as InlineThinkingPayload;
+ return [
+ {
+ type: "inline_thinking.done",
+ ...head,
+ mime_type: p.mime_type,
+ data: p.data,
+ stop_reason: p.stop_reason ?? "completed",
+ },
+ ];
+ }
+ case "approval_decision": {
+ const p = msg.payload as ApprovalDecisionPayload;
+ return [
+ { type: "approval.decided", ...head, tool_call_id: p.tool_call_id, decision: p.decision },
+ ];
+ }
+ case "abort": {
+ const p = msg.payload as AbortPayload;
+ if (main) {
+ this.abort = {
+ code: p.error_code ?? "user_abort",
+ message: p.error_message ?? p.reason ?? "The run was interrupted.",
+ };
+ }
+ return [];
+ }
+ case "request_begin": {
+ const n = (this.ordinals.get(key) ?? 0) + 1;
+ this.ordinals.set(key, n);
+ this.requests += 1;
+ // The run went on: a compaction that failed at a Task boundary was not its end.
+ if (main) this.terminal = null;
+ return [{ type: "request.started", ...head, request: n }];
+ }
+ case "token_usage": {
+ const p = msg.payload as TokenUsagePayload;
+ const request = counts(p.request);
+ if (compacting) {
+ const sum = this.compactions.get(key) ?? null;
+ this.compactions.set(key, sum === null ? request : add(sum, request));
+ } else {
+ this.heldUsage.set(key, request);
+ }
+ if (main) this.sessionUsage = counts(p.session);
+ return [];
+ }
+ case "request_end": {
+ const p = msg.payload as RequestEndPayload;
+ const usage = this.heldUsage.get(key) ?? null;
+ this.heldUsage.delete(key);
+ if (usage !== null) this.usage = add(this.usage, usage);
+ const error = errorOf(p);
+ if (main && p.status !== "completed" && p.retry_in_ms === undefined) {
+ this.terminal = { status: p.status, ...errorProp(error) };
+ }
+ return [
+ {
+ type: "request.done",
+ ...head,
+ request: this.ordinals.get(key) ?? 0,
+ status: p.status,
+ usage,
+ ...errorProp(error),
+ ...(p.attempt !== undefined ? { attempt: p.attempt } : {}),
+ ...(p.retry_in_ms !== undefined ? { retry_in_ms: p.retry_in_ms } : {}),
+ },
+ ];
+ }
+ case "compaction_begin": {
+ const p = msg.payload as CompactionBeginPayload;
+ this.compactions.set(key, null);
+ return [
+ {
+ type: "compaction.started",
+ ...head,
+ reason: p.reason,
+ mode: p.mode,
+ context: p.context,
+ turns: p.turns,
+ },
+ ];
+ }
+ case "compaction_end": {
+ const p = msg.payload as CompactionEndPayload;
+ const usage = this.compactions.get(key) ?? null;
+ this.compactions.delete(key);
+ if (usage !== null) this.usage = add(this.usage, usage);
+ const error = errorOf(p);
+ if (main && p.status !== "completed") {
+ this.terminal = { status: p.status, ...errorProp(error) };
+ }
+ return [
+ {
+ type: "compaction.done",
+ ...head,
+ reason: p.reason,
+ mode: p.mode,
+ status: p.status,
+ usage,
+ ...errorProp(error),
+ ...(p.attempt !== undefined ? { attempt: p.attempt } : {}),
+ },
+ ];
+ }
+ case "hook": {
+ const p = msg.payload as HookPayload;
+ return [
+ {
+ type: "hook.fired",
+ ...head,
+ hook: p.hook,
+ name: p.name,
+ ...(p.decision !== undefined ? { decision: p.decision } : {}),
+ ...(p.reason !== undefined ? { reason: p.reason } : {}),
+ ...(p.output !== undefined ? { output: { ...p.output } } : {}),
+ },
+ ];
+ }
+ case "mcp_connect_begin": {
+ const p = msg.payload as McpConnectBeginPayload;
+ return [{ type: "mcp_connect.started", ...head, servers: [...p.servers] }];
+ }
+ case "mcp_connect_end": {
+ const p = msg.payload as McpConnectEndPayload;
+ return [
+ {
+ type: "mcp_connect.done",
+ ...head,
+ status: p.status,
+ results: p.results.map((r) => ({
+ server: r.server,
+ transport: r.transport,
+ status: r.status,
+ duration_ms: r.duration_ms,
+ ...(r.tools !== undefined ? { tools: r.tools } : {}),
+ ...errorProp(errorOf(r)),
+ })),
+ ...errorProp(errorOf(p)),
+ },
+ ];
+ }
+ case "tool_list_ready": {
+ const p = msg.payload as ToolListReadyPayload;
+ return [{ type: "tools.ready", ...head, tools: p.tools.map((t) => ({ ...t })) }];
+ }
+ // `subagent` pointers are Trace-only; anything else is not part of AMSP.
+ default:
+ return [];
+ }
+ }
+}
diff --git a/packages/server/src/amsp/try-route.ts b/packages/server/src/amsp/try-route.ts
new file mode 100644
index 00000000..615c015b
--- /dev/null
+++ b/packages/server/src/amsp/try-route.ts
@@ -0,0 +1,48 @@
+/**
+ * The API tab's Try it: `POST /api/projects/:projectId/agents/:agentId/api/try` runs the Agent
+ * once through the Agent API's own run handler (run-stream.ts), for the Project owner's sign-in
+ * instead of a key. The body is the public route's `RunRequest`, the answer the same AMSP stream
+ * or the same JSON refusals, so the tab shows exactly what a program calling the Agent receives.
+ *
+ * It answers only while the API would: the admin's switch off is 403 `agent_api_disabled`, the
+ * Agent's switch off (or no such Agent) is 404 `agent_not_found`, as on the public routes. No key
+ * is presented, so none is stamped as used. The Session a run creates is an ordinary API Session
+ * of the Agent — source `api`, client `api`, the Agent's API approval mode — and nothing marks
+ * who was at the keyboard.
+ *
+ * Owner only: the tab puts it among the owner's controls, and a run starts under the approval
+ * mode the owner set for programs. A member talks to the Agent in the composer. And the owner's
+ * sign-in only, like the tab's writes: the local API token is refused with 403 `human_required`
+ * (requireHuman), before anything else is checked.
+ */
+import { Hono } from "hono";
+import { requireHuman } from "../auth/middleware.js";
+import type { AppEnv } from "../auth/middleware.js";
+import { requireValidId } from "../http/validate.js";
+import type { Access } from "../mechanisms/projects.js";
+import type { AmspEnv } from "./gate.js";
+import { requireAgentApiOn, requireExposedAgent } from "./gate.js";
+import type { AmspRouteDeps } from "./routes.js";
+import { runStream } from "./run-stream.js";
+
+export interface AgentApiTryRouteDeps extends AmspRouteDeps {
+ access: Pick<Access, "requireProjectOwner">;
+}
+
+export function agentApiTryRoutes(deps: AgentApiTryRouteDeps): Hono<AppEnv> {
+ const app = new Hono<AmspEnv>();
+
+ app.post("/", async (c) => {
+ requireHuman(c);
+ const projectId = requireValidId(c, "projectId");
+ const agentId = requireValidId(c, "agentId");
+ // 404 for a Project the caller cannot reach, 403 `owner_required` for a member.
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
+ requireAgentApiOn(deps.settings);
+ await requireExposedAgent(deps, projectId, agentId);
+ c.set("amsp", { projectId, agentId, keyId: null, session: null });
+ return runStream(c, deps);
+ });
+
+ return app as unknown as Hono<AppEnv>;
+}
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 50d1f631..5ce5427e 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -294,6 +294,12 @@ export interface ServerSettings {
* reports it so clients hide the mode switch. Organizations on disk are untouched.
*/
companyMode: boolean;
+ /**
+ * Whether external programs may talk to Agents through the Agent API (default on). Off answers
+ * every `/api/amsp/v1` request 403 `agent_api_disabled` (a CORS preflight excepted); every
+ * Agent's API switch, approval mode and keys are kept, so turning it on again restores them.
+ */
+ agentApiEnabled: boolean;
}
export interface ServerSettingsResponse {
@@ -527,6 +533,8 @@ export interface ServerSettingsUpdateRequest {
proxyForAgent?: boolean;
/** Company mode master switch; see `ServerSettings.companyMode`. */
companyMode?: boolean;
+ /** Agent API switch; see `ServerSettings.agentApiEnabled`. */
+ agentApiEnabled?: boolean;
/**
* New proxy address. Accepted forms: any proxy URL undici's dispatcher takes —
* `http://`, `https://`, `socks5://` / `socks://`, credentials allowed — or bare
@@ -1420,6 +1428,8 @@ export interface AgentSummary {
pluginUpdates: PluginUpdateRef[];
/** Memory count (topic files summed over the scope directories under agent_state/memory/, independent of the memory switch). */
memoryCount: number;
+ /** Whether the Agent's API tab switch is on (this server's web.db, see AgentApiSettings.enabled): the list card's API mark. */
+ apiEnabled: boolean;
}
export interface AgentsResponse {
@@ -1614,6 +1624,72 @@ export interface AgentConfigUpdateRequest {
};
}
+// ---------------------------------------------------------------------------
+// Agent API (/api/projects/:projectId/agents/:agentId/api; the stream itself is AMSP,
+// /api/amsp/v1, whose snake_case wire types live in @lmliheng/amsp)
+// ---------------------------------------------------------------------------
+
+/** One API key of an Agent, as listed: the secret itself is shown once, at creation, and never again. */
+export interface AgentApiKeyInfo {
+ keyId: string;
+ /** 1-64 characters, given by whoever created it. */
+ name: string;
+ /** The key's first 16 characters (`penguin_` + 8), enough to tell keys apart. */
+ prefix: string;
+ /** user_id of the Project owner who created it. */
+ createdBy: string;
+ createdAt: string;
+ /** Last run request that authenticated with it; null = never used. */
+ lastUsedAt: string | null;
+}
+
+/**
+ * One Agent's public API settings — this server's, kept in web.db, never in the Agent State or
+ * the Project file, so the Agent cannot expose itself or loosen its own approvals. An Agent
+ * never configured reads as disabled, keyed, allow-all, with no keys.
+ */
+export interface AgentApiSettings {
+ /** The API tab's switch; off = every AMSP request for this Agent is 404 `agent_not_found`. */
+ enabled: boolean;
+ /** Keyless access: a request without `Authorization` is accepted; off = 401 `unauthorized`. */
+ open: boolean;
+ /**
+ * The approval mode an API Session is created with. It is copied onto each API Session when
+ * that Session is created, and the Session's own mode is what every decision reads, so a
+ * change here applies to API Sessions created afterwards.
+ */
+ approvalMode: ApprovalMode;
+ keys: AgentApiKeyInfo[];
+}
+
+export interface AgentApiResponse {
+ api: AgentApiSettings;
+ /**
+ * The admin's server-wide switch (`ServerSettings.agentApiEnabled`), which only an admin can
+ * read through /api/admin/settings: off, every Agent's API is refused (403) whatever `api` says.
+ */
+ serverEnabled: boolean;
+}
+
+/** PUT body (owner only): every field optional, omitted fields keep their current value. */
+export interface AgentApiUpdateRequest {
+ enabled?: boolean;
+ open?: boolean;
+ approvalMode?: ApprovalMode;
+}
+
+/** POST …/api/keys body (owner only). */
+export interface AgentApiKeyCreateRequest {
+ /** 1-64 characters. */
+ name: string;
+}
+
+/** The one response that carries the secret (`penguin_` + 43 base64url characters); only its hash is stored. */
+export interface AgentApiKeyCreateResponse {
+ key: AgentApiKeyInfo;
+ secret: string;
+}
+
// ---------------------------------------------------------------------------
// Memory
// ---------------------------------------------------------------------------
@@ -1930,14 +2006,14 @@ export interface SessionInfo {
/**
* Which client opened the Session, as stored on the index row: "cli" from the CLI (a
* Session adopted from a legacy CLI-direct Trace included), "org" from the organization
- * runtime (a desk or a ticket session, and every sub-session one of those spawns), "web"
- * otherwise. Absent only on a row that
- * predates the column, which reads as "web". Unlike {@link SessionInfo.orgId} — projected
- * from the organization caches, so it disappears with the organization and is not read
- * while company mode is off — this is a durable stamp on the row: development mode's list
- * hides an "org" Session either way.
- */
- client?: "web" | "cli" | "org";
+ * runtime (a desk or a ticket session, and every sub-session one of those spawns), "api"
+ * from an Agent API run (the only Sessions the API may continue), "web" otherwise. Absent
+ * only on a row that predates the column, which reads as "web". Unlike
+ * {@link SessionInfo.orgId} — projected from the organization caches, so it disappears with
+ * the organization and is not read while company mode is off — this is a durable stamp on
+ * the row: development mode's list hides an "org" Session either way.
+ */
+ client?: "web" | "cli" | "org" | "api";
/**
* Background work the Session's loaded runtime still owns: command sessions running past
* their yield window (`exec_command` promotions and `run_in_background` launches) and
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index d0b15e9e..c3a1bf1f 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -60,6 +60,7 @@ import { UiPrefsRepo } from "./db/repos/ui-prefs.js";
import { UsersRepo } from "./db/repos/users.js";
import type { UserRow } from "./db/repos/users.js";
import { jsonOnlyWrites } from "./auth/middleware.js";
+import { AMSP_PREFIX, amspAllowOrigin } from "./amsp/cors.js";
import { mintApiToken, storeApiToken } from "./auth/api-token.js";
import type { Identity } from "./terminal/identity.js";
import { terminalRoutes } from "./terminal/routes.js";
@@ -454,6 +455,10 @@ export function createApp(boot: ServerBoot): Hono<AppEnv> {
// 300MB bodies on a server whose limits were left at 10MB. It is re-derived per request, so an
// admin's change takes effect immediately; the middleware itself is memoized on the resulting
// size so the steady state allocates nothing.
+ //
+ // The Agent API is called from browsers too: its CORS header (amsp/cors.ts) has to reach these
+ // two refusals, which answer before its group runs, or a caller reads a CORS failure, not the code.
+ app.use(`${AMSP_PREFIX}/*`, amspAllowOrigin);
let capped: { size: number; mw: MiddlewareHandler } | null = null;
app.use("/api/*", (c, next) => {
const size = bodyLimitBytes(settings().getAttachmentLimitsMb());
diff --git a/packages/server/src/auth/middleware.ts b/packages/server/src/auth/middleware.ts
index f6be096b..0964b70b 100644
--- a/packages/server/src/auth/middleware.ts
+++ b/packages/server/src/auth/middleware.ts
@@ -7,7 +7,8 @@
* applies to every route behind this middleware, SSE endpoints included (the CLI
* consumes SSE via fetch with headers). A Bearer header that does not match fails the
* request rather than falling back to the cookie: silently downgrading a wrong explicit
- * credential would mask misconfiguration.
+ * credential would mask misconfiguration. A few writes refuse the token all the same and take a
+ * person's sign-in (requireHuman).
*
* Accessing a protected API while logged out -> 401 `{error:{code:"unauthorized"}}`.
* CSRF: SameSite=Lax plus a Content-Type an HTML form cannot forge (see jsonOnlyWrites).
@@ -101,6 +102,33 @@ export function bearerToken(header: string | undefined): string | null {
return m === null ? null : m[1]!.trim();
}
+/**
+ * Refuses the local API token on a write that only a person may make: 403 `human_required`. A
+ * person's sign-in — a cookie session, from the Web App, `penguin auth login` or
+ * `penguin auth token` — passes. Every tool subprocess of a server-driven Session holds that token
+ * as `ADELIE_API_TOKEN`, so these are the writes an Agent must not make from its own shell:
+ *
+ * - who can reach an Agent from outside — its API switch, keyless access and approval mode, its
+ * keys, the API tab's Try it, and the admin's `agentApiEnabled` (http/routes/agent-api.ts,
+ * amsp/try-route.ts, http/routes/admin-settings.ts).
+ *
+ * This narrows the credential the harness hands an Agent; it is not a boundary. A process that
+ * runs as the data root's OS user outside the sandbox can mint a sign-in of its own
+ * (`penguin auth token`), or reset a password with the token and sign in. The sandbox is the
+ * boundary. A per-Session credential (design PR #235) is the structural fix: when it lands, this
+ * check becomes "a Session's credential is refused, a person's login is not", and the routes
+ * calling it do not change.
+ */
+export function requireHuman(c: { var: { sessionVia: SessionVia } }): void {
+ if (c.var.sessionVia === "token") {
+ throw new HttpError(
+ 403,
+ "human_required",
+ "Only the signed-in user can do this, in the app; an API token cannot.",
+ );
+ }
+}
+
const WRITE_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
/**
diff --git a/packages/server/src/builtin-browser/routes.ts b/packages/server/src/builtin-browser/routes.ts
index 4addc0b9..40c3541b 100644
--- a/packages/server/src/builtin-browser/routes.ts
+++ b/packages/server/src/builtin-browser/routes.ts
@@ -33,6 +33,7 @@ import type {
BuiltinBrowserStatus,
BuiltinBrowserTab,
} from "../api/types.js";
+import { requireHuman } from "../auth/middleware.js";
import type { AppEnv } from "../auth/middleware.js";
import { HttpError } from "../http/errors.js";
import { badRequest } from "../http/validate.js";
diff --git a/packages/server/src/db/migrations.ts b/packages/server/src/db/migrations.ts
index d93cd489..1f56df47 100644
--- a/packages/server/src/db/migrations.ts
+++ b/packages/server/src/db/migrations.ts
@@ -581,6 +581,52 @@ export const MIGRATIONS: readonly Migration[] = [
if (has("cost")) db.exec("ALTER TABLE usage_records DROP COLUMN cost");
},
},
+ {
+ version: 15,
+ name: "agent-api",
+ // Additive: two new tables and an index. The Agent API's per-Agent settings (the switch,
+ // keyless access, the approval mode API Sessions are created with) and its keys, stored
+ // hashed. A predecessor build never reads them and serves no /api/amsp route, so a
+ // rollback survives it: callers get 404 until a build that knows the tables is back.
+ swapSafe: true,
+ up(db) {
+ // Frozen copy of the DDL as of the Agent API feature; do not re-derive from schema.ts.
+ // IF NOT EXISTS because the declarative track may already have created them (ADOPTION).
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS agent_api ( -- per-Agent public API settings (amsp/routes.ts); NOT rebuildable from files
+ project_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ enabled INTEGER NOT NULL DEFAULT 0,
+ open INTEGER NOT NULL DEFAULT 0,
+ approval_mode TEXT NOT NULL DEFAULT 'allow-all',
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (project_id, agent_id)
+ );
+ CREATE TABLE IF NOT EXISTS agent_api_keys ( -- one row per key the API tab or the CLI minted; the caller alone holds the key
+ key_id TEXT PRIMARY KEY,
+ project_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ token_hash TEXT NOT NULL UNIQUE,
+ prefix TEXT NOT NULL,
+ name TEXT NOT NULL,
+ created_by TEXT NOT NULL REFERENCES users(user_id),
+ created_at TEXT NOT NULL,
+ last_used_at TEXT
+ );
+ CREATE INDEX IF NOT EXISTS idx_agent_api_keys_agent ON agent_api_keys(project_id, agent_id);
+ `);
+ },
+ // LOSES every Agent's API settings and every key: each exposed Agent reads as disabled
+ // again (404 to its callers), and every caller needs a newly created key once it is back
+ // on — no file holds a copy of either.
+ down(db) {
+ db.exec(`
+ DROP INDEX IF EXISTS idx_agent_api_keys_agent;
+ DROP TABLE IF EXISTS agent_api_keys;
+ DROP TABLE IF EXISTS agent_api;
+ `);
+ },
+ },
];
/** The highest version this build knows how to reach. */
diff --git a/packages/server/src/db/repos/agent-api.ts b/packages/server/src/db/repos/agent-api.ts
new file mode 100644
index 00000000..4c2d1ad7
--- /dev/null
+++ b/packages/server/src/db/repos/agent-api.ts
@@ -0,0 +1,149 @@
+/**
+ * agent_api / agent_api_keys tables repo: each Agent's public API settings (the switch, keyless
+ * access, the approval mode its API Sessions are created with) and its keys, stored as sha256
+ * hashes — the caller alone holds a key. Neither table is rebuildable from files: dropping them
+ * turns every exposed Agent off and invalidates every key.
+ */
+import { Component, Use } from "@lmliheng/penguin-core/kernel";
+import type { ApprovalMode } from "../../api/types.js";
+import type { Db } from "../../hmr/capabilities.js";
+import type {
+ AgentApi,
+ AgentApiKeyRow,
+ AgentApiPatch,
+ AgentApiRow,
+} from "../../mechanisms/agent-api.js";
+
+type Row = Record<string, unknown>;
+
+function settingsOf(r: Row): AgentApiRow {
+ return {
+ projectId: r.project_id as string,
+ agentId: r.agent_id as string,
+ enabled: Number(r.enabled) === 1,
+ open: Number(r.open) === 1,
+ approvalMode: r.approval_mode as ApprovalMode,
+ updatedAt: r.updated_at as string,
+ };
+}
+
+function keyOf(r: Row): AgentApiKeyRow {
+ return {
+ keyId: r.key_id as string,
+ projectId: r.project_id as string,
+ agentId: r.agent_id as string,
+ prefix: r.prefix as string,
+ name: r.name as string,
+ createdBy: r.created_by as string,
+ createdAt: r.created_at as string,
+ lastUsedAt: (r.last_used_at as string | null) ?? null,
+ };
+}
+
+@Component()
+export class AgentApiRepo implements AgentApi {
+ @Use() private readonly db!: Db;
+
+ get(projectId: string, agentId: string): AgentApiRow | null {
+ const r = this.db
+ .prepare("SELECT * FROM agent_api WHERE project_id = ? AND agent_id = ?")
+ .get(projectId, agentId);
+ return r ? settingsOf(r as Row) : null;
+ }
+
+ set(projectId: string, agentId: string, patch: AgentApiPatch, at: string): AgentApiRow {
+ const current = this.get(projectId, agentId);
+ const next: AgentApiRow = {
+ projectId,
+ agentId,
+ enabled: patch.enabled ?? current?.enabled ?? false,
+ open: patch.open ?? current?.open ?? false,
+ approvalMode: patch.approvalMode ?? current?.approvalMode ?? "allow-all",
+ updatedAt: at,
+ };
+ this.db
+ .prepare(
+ `INSERT INTO agent_api (project_id, agent_id, enabled, open, approval_mode, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?)
+ ON CONFLICT(project_id, agent_id) DO UPDATE SET
+ enabled = excluded.enabled, open = excluded.open,
+ approval_mode = excluded.approval_mode, updated_at = excluded.updated_at`,
+ )
+ .run(
+ projectId,
+ agentId,
+ next.enabled ? 1 : 0,
+ next.open ? 1 : 0,
+ next.approvalMode,
+ next.updatedAt,
+ );
+ return next;
+ }
+
+ enabledAgents(projectId: string): string[] {
+ const rows = this.db
+ .prepare("SELECT agent_id FROM agent_api WHERE project_id = ? AND enabled = 1")
+ .all(projectId) as Row[];
+ return rows.map((r) => r.agent_id as string);
+ }
+
+ listKeys(projectId: string, agentId: string): AgentApiKeyRow[] {
+ const rows = this.db
+ .prepare(
+ `SELECT * FROM agent_api_keys WHERE project_id = ? AND agent_id = ?
+ ORDER BY created_at, key_id`,
+ )
+ .all(projectId, agentId) as Row[];
+ return rows.map(keyOf);
+ }
+
+ insertKey(row: AgentApiKeyRow & { tokenHash: string }): void {
+ this.db
+ .prepare(
+ `INSERT INTO agent_api_keys
+ (key_id, project_id, agent_id, token_hash, prefix, name, created_by, created_at, last_used_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ )
+ .run(
+ row.keyId,
+ row.projectId,
+ row.agentId,
+ row.tokenHash,
+ row.prefix,
+ row.name,
+ row.createdBy,
+ row.createdAt,
+ row.lastUsedAt,
+ );
+ }
+
+ findKeyByHash(tokenHash: string): AgentApiKeyRow | null {
+ const r = this.db.prepare("SELECT * FROM agent_api_keys WHERE token_hash = ?").get(tokenHash);
+ return r ? keyOf(r as Row) : null;
+ }
+
+ touchKey(keyId: string, at: string): void {
+ this.db.prepare("UPDATE agent_api_keys SET last_used_at = ? WHERE key_id = ?").run(at, keyId);
+ }
+
+ deleteKey(projectId: string, agentId: string, keyId: string): boolean {
+ const result = this.db
+ .prepare("DELETE FROM agent_api_keys WHERE key_id = ? AND project_id = ? AND agent_id = ?")
+ .run(keyId, projectId, agentId);
+ return Number(result.changes) > 0;
+ }
+
+ deleteByAgent(projectId: string, agentId: string): void {
+ this.db
+ .prepare("DELETE FROM agent_api_keys WHERE project_id = ? AND agent_id = ?")
+ .run(projectId, agentId);
+ this.db
+ .prepare("DELETE FROM agent_api WHERE project_id = ? AND agent_id = ?")
+ .run(projectId, agentId);
+ }
+
+ deleteByProject(projectId: string): void {
+ this.db.prepare("DELETE FROM agent_api_keys WHERE project_id = ?").run(projectId);
+ this.db.prepare("DELETE FROM agent_api WHERE project_id = ?").run(projectId);
+ }
+}
diff --git a/packages/server/src/db/repos/server-settings.ts b/packages/server/src/db/repos/server-settings.ts
index a5d71ba9..7c3c2438 100644
--- a/packages/server/src/db/repos/server-settings.ts
+++ b/packages/server/src/db/repos/server-settings.ts
@@ -36,6 +36,8 @@ const ATTACHMENT_MAX_MB_KEY = "attachment_max_mb";
const ATTACHMENT_TOTAL_MB_KEY = "attachment_total_mb";
/** Key of the company-mode master switch; default off (see getCompanyMode). */
const COMPANY_MODE_KEY = "companyMode";
+/** Key of the Agent API switch; default on (see getAgentApiEnabled). */
+const AGENT_API_KEY = "agentApiEnabled";
@Component()
export class ServerSettingsRepo implements Settings {
@@ -167,4 +169,17 @@ export class ServerSettingsRepo implements Settings {
setCompanyMode(value: boolean): void {
this.set(COMPANY_MODE_KEY, JSON.stringify(value));
}
+
+ /**
+ * Whether external programs may reach Agents through the Agent API (default ON): only a stored
+ * `false` turns it off, so an unreadable row leaves the feature as it ships. Read per request
+ * by the `/api/amsp/v1` gate, so flipping it needs no restart.
+ */
+ getAgentApiEnabled(): boolean {
+ return this.get(AGENT_API_KEY) !== "false";
+ }
+
+ setAgentApiEnabled(value: boolean): void {
+ this.set(AGENT_API_KEY, JSON.stringify(value));
+ }
}
diff --git a/packages/server/src/db/repos/sessions.ts b/packages/server/src/db/repos/sessions.ts
index a1c97549..aef20cb1 100644
--- a/packages/server/src/db/repos/sessions.ts
+++ b/packages/server/src/db/repos/sessions.ts
@@ -37,8 +37,9 @@ export interface SessionRow {
* Creating client: "web" (created via the Web App), "cli" (created through the API by
* the CLI, or adopted from a Trace a legacy CLI-direct run left behind), "org" (opened by
* the organization runtime — a desk or a ticket session — or spawned as a sub-session of
- * one, which inherits the stamp at registration); NULL = legacy row from before the column
- * existed, treated as web. Free text in SQLite, so a new value needs no migration.
+ * one, which inherits the stamp at registration), "api" (created by an Agent API run — the
+ * only rows the API may continue); NULL = legacy row from before the column existed,
+ * treated as web. Free text in SQLite, so a new value needs no migration.
* Provenance that outlives its organization: development mode's list is the one reader
* that filters on it (through the list's `excludeOrg`), and it hides "org" rows whether or
* not the organization still exists. The schedule/subagent SOURCE is deliberately NOT a row field — core
@@ -46,7 +47,7 @@ export interface SessionRow {
* (runtime/session-sources.ts); `client` is a separate, DB-only axis that meta never
* records.
*/
- client?: "web" | "cli" | "org" | null;
+ client?: "web" | "cli" | "org" | "api" | null;
/** Cache: a Trace record exists (set at task start / adoption / subagent registration; backfilled by list hydration). */
hasTrace?: boolean;
/**
@@ -100,7 +101,7 @@ function mapRow(r: Record<string, unknown>): SessionRow {
thinkingLevel: (r.thinking_level as ThinkingLevelName | null) ?? null,
title: (r.title as string | null) ?? null,
archivedAt: (r.archived_at as string | null) ?? null,
- client: (r.client as "web" | "cli" | "org" | null) ?? null,
+ client: (r.client as "web" | "cli" | "org" | "api" | null) ?? null,
hasTrace: (r.has_trace as number) === 1,
// The open-time backfill leaves no NULLs; the coalesce only hardens against a row
// somehow inserted as NULL (degrades to createdAt instead of surfacing undefined).
diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.ts
index b838b93e..519ab112 100644
--- a/packages/server/src/db/schema.ts
+++ b/packages/server/src/db/schema.ts
@@ -88,7 +88,7 @@ CREATE TABLE IF NOT EXISTS sessions (
thinking_level TEXT, -- level pinned for THIS session (none|low|medium|high|xhigh|max); NULL=not pinned, runs follow the Agent config
title TEXT, -- auto-generated by the model after the first exchange; NULL=not yet (frontend shows "New chat")
archived_at TEXT, -- archive time; NULL=not archived (shown by default; archived ones move under "Archived")
- client TEXT, -- creating client: 'web' (created via the Web App) | 'cli' (adopted from a CLI Trace); NULL = legacy row, treated as web
+ client TEXT, -- creating client: 'web' (created via the Web App) | 'cli' (adopted from a CLI Trace) | 'org' (company mode) | 'api' (an Agent API run); NULL = legacy row, treated as web
has_trace INTEGER NOT NULL DEFAULT 0, -- cache: a Trace record exists (set at task start / adoption / subagent registration; lazily backfilled by list hydration)
fork_count INTEGER NOT NULL DEFAULT 0, -- monotonically allocated child-fork number for this source Session; never decremented when a fork is deleted
sandbox TEXT, -- the Session's sandbox policy snapshot (JSON SandboxSettings); NULL = legacy row, snapshotted at its next command
@@ -165,6 +165,27 @@ CREATE TABLE IF NOT EXISTS ui_prefs (
user_id TEXT PRIMARY KEY REFERENCES users(user_id) ON DELETE CASCADE,
prefs_json TEXT NOT NULL -- {theme?, lastProjectId?, ...} free-form JSON
);
+CREATE TABLE IF NOT EXISTS agent_api ( -- per-Agent public API settings (amsp/routes.ts); NOT rebuildable from files
+ project_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ enabled INTEGER NOT NULL DEFAULT 0, -- the API tab's switch; off = every /api/amsp request for it is 404 agent_not_found
+ open INTEGER NOT NULL DEFAULT 0, -- keyless access: a request without Authorization is accepted; off = 401 unauthorized
+ approval_mode TEXT NOT NULL DEFAULT 'allow-all', -- the approval mode an API Session is CREATED with (allow-all|deny-all|read-only|always-ask); copied onto sessions.approval_mode, never read per decision
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (project_id, agent_id)
+);
+CREATE TABLE IF NOT EXISTS agent_api_keys ( -- one row per key the API tab or the CLI minted; the caller alone holds the key
+ key_id TEXT PRIMARY KEY, -- 16 base64url chars, shown in the list
+ project_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ token_hash TEXT NOT NULL UNIQUE, -- sha256(key) hex
+ prefix TEXT NOT NULL, -- the key's first 16 characters ("penguin_" + 8), shown in the list
+ name TEXT NOT NULL, -- 1-64 characters
+ created_by TEXT NOT NULL REFERENCES users(user_id),
+ created_at TEXT NOT NULL,
+ last_used_at TEXT -- stamped once per run request that authenticated with it; NULL = never
+);
+CREATE INDEX IF NOT EXISTS idx_agent_api_keys_agent ON agent_api_keys(project_id, agent_id);
CREATE TABLE IF NOT EXISTS server_settings ( -- admin-level server-global settings (GET/PUT /api/admin/settings)
key TEXT PRIMARY KEY, -- setting name, e.g. 'proxy_for_app'
value TEXT NOT NULL -- JSON-encoded value; an absent row means the setting's built-in default
diff --git a/packages/server/src/http/app.ts b/packages/server/src/http/app.ts
index 436484c3..15e7b4e3 100644
--- a/packages/server/src/http/app.ts
+++ b/packages/server/src/http/app.ts
@@ -6,6 +6,7 @@ import { Config, Log } from "../hmr/capabilities.js";
import type { MiddlewareHandler } from "hono";
import { bodyLimit } from "hono/body-limit";
import { authMiddleware, jsonOnlyWrites } from "../auth/middleware.js";
+import { AMSP_PREFIX, amspAllowOrigin } from "../amsp/cors.js";
import { HttpError, handleError } from "./errors.js";
import { attributedProjectId } from "./attribution.js";
import { bodyLimitBytes } from "../services/attachment-limits.js";
@@ -68,6 +69,10 @@ export class HttpModule {
`${c.req.method} ${c.req.path} ${c.res.status} ${Math.round(performance.now() - start)}ms`,
);
});
+ // The same header the host layer puts ahead of its copies of these two checks (src/app.ts):
+ // their refusals answer before the Agent API's group runs, and a browser caller must read the
+ // code, not a CORS failure.
+ app.use(`${AMSP_PREFIX}/*`, amspAllowOrigin);
let capped: { size: number; mw: MiddlewareHandler } | null = null;
app.use("/api/*", (c, next) => {
const size = bodyLimitBytes(this.settings.getAttachmentLimitsMb());
diff --git a/packages/server/src/http/routes/admin-settings.ts b/packages/server/src/http/routes/admin-settings.ts
index 03ead49b..cbf1d0a5 100644
--- a/packages/server/src/http/routes/admin-settings.ts
+++ b/packages/server/src/http/routes/admin-settings.ts
@@ -3,13 +3,16 @@
* GET|PUT /api/admin/settings — the server-global settings stored in server_settings:
* the proxy settings (the "application uses the proxy" and "agent environment uses the
* proxy" switches and their shared explicit address) and the upload limits (the
- * per-file and per-message attachment caps, in whole MB).
+ * per-file and per-message attachment caps, in whole MB) and the Agent API switch.
* A PUT applies immediately: everything is validated first (a rejected request writes
* nothing), then the persisted values are written, then the process dispatcher is
* rebuilt so new outbound connections follow the change without a restart (the agent
* switch needs no push — the command-subprocess policy getter re-reads the repo at
* every spawn). The upload limits need no push either, for the same reason: the
* attachment validators and the request body cap both read the repo per request.
+ * A PUT carrying `agentApiEnabled` takes a person's sign-in: the local API token is refused
+ * with 403 `human_required`, and nothing in that body is written. The token may change every
+ * other field.
*
* GET /api/admin/settings/proxy-probe names the model provider hosts the reachability probe
* would request; POST .../proxy-probe/:provider measures one of them — unauthenticated, see
@@ -22,6 +25,7 @@ import type {
ServerSettingsResponse,
} from "../../api/types.js";
import { HttpError } from "../errors.js";
+import { requireHuman } from "../../auth/middleware.js";
import type { AppEnv } from "../../auth/middleware.js";
import { optionalBoolean, readJson } from "../validate.js";
import type { ProxyControl } from "../../hmr/capabilities.js";
@@ -93,6 +97,7 @@ export function adminSettingsRoutes(deps: AdminSettingsRouteDeps): Hono<AppEnv>
proxyUrl: deps.serverSettingsRepo.getProxyUrl(),
...deps.serverSettingsRepo.getAttachmentLimitsMb(),
companyMode: deps.serverSettingsRepo.getCompanyMode(),
+ agentApiEnabled: deps.serverSettingsRepo.getAgentApiEnabled(),
},
});
@@ -100,11 +105,16 @@ export function adminSettingsRoutes(deps: AdminSettingsRouteDeps): Hono<AppEnv>
app.put("/", async (c) => {
const body = await readJson(c);
+ // The Agent API switch decides whether any Agent can be reached from outside, so it takes a
+ // person's sign-in, never the local API token every tool subprocess holds (see
+ // requireHuman). Refused before any field is written.
+ if (body.agentApiEnabled !== undefined) requireHuman(c);
// Validate every provided field before writing any: a partial PUT with one invalid
// field must leave the others untouched too.
const proxyForApp = optionalBoolean(body, "proxyForApp");
const proxyForAgent = optionalBoolean(body, "proxyForAgent");
const companyMode = optionalBoolean(body, "companyMode");
+ const agentApiEnabled = optionalBoolean(body, "agentApiEnabled");
const proxyUrlProvided = body.proxyUrl !== undefined;
const proxyUrl = proxyUrlProvided ? parseProxyUrl(body.proxyUrl) : null;
const attachmentMaxMb =
@@ -132,6 +142,9 @@ export function adminSettingsRoutes(deps: AdminSettingsRouteDeps): Hono<AppEnv>
// Read per tick by the organization scheduler and per request by the organization routes, so
// flipping it needs no restart: off holds every automatic trigger and 404s the routes.
if (companyMode !== undefined) deps.serverSettingsRepo.setCompanyMode(companyMode);
+ // Read per request by the /api/amsp/v1 gate: off refuses every Agent API call from the next
+ // request on (403 agent_api_disabled); each Agent's switch, approval mode and keys stay.
+ if (agentApiEnabled !== undefined) deps.serverSettingsRepo.setAgentApiEnabled(agentApiEnabled);
if (proxyForApp !== undefined) deps.serverSettingsRepo.setProxyForApp(proxyForApp);
if (proxyForAgent !== undefined) deps.serverSettingsRepo.setProxyForAgent(proxyForAgent);
if (proxyUrlProvided) deps.serverSettingsRepo.setProxyUrl(proxyUrl);
diff --git a/packages/server/src/http/routes/agent-api.ts b/packages/server/src/http/routes/agent-api.ts
new file mode 100644
index 00000000..e5c375ba
--- /dev/null
+++ b/packages/server/src/http/routes/agent-api.ts
@@ -0,0 +1,154 @@
+/**
+ * Agent API management (`/api/projects/:projectId/agents/:agentId/api`): the API tab and
+ * `penguin agent api` read and change one Agent's exposure here.
+ *
+ * GET / member the switch, keyless access, the approval mode, the keys
+ * PUT / owner change the switch, keyless access and/or the approval mode
+ * POST /keys owner create a key: the secret is in this response and nowhere else
+ * DELETE /keys/:keyId owner delete a key: its next request is refused
+ *
+ * Owner means the Project owner, the rule Agent deletion uses: exposing an Agent to programs
+ * outside the Web App is a Project-level decision, and so is the approval mode those programs'
+ * conversations start with. The settings live in this server's web.db (see AgentApi), never in
+ * the Agent State the Agent itself can rewrite. And the writes take the owner's sign-in, never
+ * the local API token every tool subprocess holds (403 `human_required`, see requireHuman): an
+ * Agent must not switch on its own exposure from its shell. The reads stay open to the token,
+ * for `penguin agent api status` and `keys ls`.
+ */
+import { Hono } from "hono";
+import type { Context } from "hono";
+import type {
+ AgentApiKeyCreateResponse,
+ AgentApiKeyInfo,
+ AgentApiResponse,
+} from "../../api/types.js";
+import { requireHuman } from "../../auth/middleware.js";
+import type { AppEnv } from "../../auth/middleware.js";
+import { mintAgentApiKey } from "../../amsp/keys.js";
+import { HttpError } from "../errors.js";
+import {
+ optionalBoolean,
+ optionalEnum,
+ readJson,
+ requireString,
+ requireValidId,
+} from "../validate.js";
+import { APPROVAL_MODES } from "./sessions.js";
+import type { AgentApi, AgentApiKeyRow } from "../../mechanisms/agent-api.js";
+import type { AgentConfig } from "../../mechanisms/agents.js";
+import type { Access } from "../../mechanisms/projects.js";
+import type { Settings } from "../../mechanisms/settings.js";
+
+/** What this route group reaches — bound by its module (services/agent-routes.ts). */
+export interface AgentApiRouteDeps {
+ agentApi: AgentApi;
+ agentConfigService: Pick<AgentConfig, "requireExists">;
+ access: Pick<Access, "requireProjectAccess" | "requireProjectOwner">;
+ settings: Pick<Settings, "getAgentApiEnabled">;
+ now: () => Date;
+}
+
+/** A key as the list shows it: never the secret, never its hash. */
+function keyInfo(row: AgentApiKeyRow): AgentApiKeyInfo {
+ return {
+ keyId: row.keyId,
+ name: row.name,
+ prefix: row.prefix,
+ createdBy: row.createdBy,
+ createdAt: row.createdAt,
+ lastUsedAt: row.lastUsedAt,
+ };
+}
+
+export function agentApiRoutes(deps: AgentApiRouteDeps): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
+
+ /** The Agent's settings as the tab reads them; a never-configured Agent reads as off, keyed, allow-all. */
+ const settings = (projectId: string, agentId: string): AgentApiResponse => {
+ const row = deps.agentApi.get(projectId, agentId);
+ return {
+ api: {
+ enabled: row?.enabled ?? false,
+ open: row?.open ?? false,
+ approvalMode: row?.approvalMode ?? "allow-all",
+ keys: deps.agentApi.listKeys(projectId, agentId).map(keyInfo),
+ },
+ // The tab says when the admin has the whole API off: only an admin can read that setting.
+ serverEnabled: deps.settings.getAgentApiEnabled(),
+ };
+ };
+
+ /** The path's Agent, once the caller may reach it (`owner` for the writes) and it exists. */
+ const agentOf = async (
+ c: Context<AppEnv>,
+ owner: boolean,
+ ): Promise<{ projectId: string; agentId: string }> => {
+ const projectId = requireValidId(c, "projectId");
+ const agentId = requireValidId(c, "agentId");
+ if (owner) deps.access.requireProjectOwner(c.var.user.userId, projectId);
+ else deps.access.requireProjectAccess(c.var.user.userId, projectId);
+ await deps.agentConfigService.requireExists(projectId, agentId);
+ return { projectId, agentId };
+ };
+
+ app.get("/", async (c) => {
+ const { projectId, agentId } = await agentOf(c, false);
+ return c.json(settings(projectId, agentId));
+ });
+
+ app.put("/", async (c) => {
+ requireHuman(c);
+ const { projectId, agentId } = await agentOf(c, true);
+ const body = await readJson(c);
+ // Every field is checked before any is written.
+ const enabled = optionalBoolean(body, "enabled");
+ const open = optionalBoolean(body, "open");
+ const approvalMode = optionalEnum(body, "approvalMode", APPROVAL_MODES);
+ deps.agentApi.set(
+ projectId,
+ agentId,
+ {
+ ...(enabled !== undefined ? { enabled } : {}),
+ ...(open !== undefined ? { open } : {}),
+ ...(approvalMode !== undefined ? { approvalMode } : {}),
+ },
+ deps.now().toISOString(),
+ );
+ return c.json(settings(projectId, agentId));
+ });
+
+ app.post("/keys", async (c) => {
+ requireHuman(c);
+ const { projectId, agentId } = await agentOf(c, true);
+ const body = await readJson(c);
+ const name = requireString(body, "name", { maxLen: 64, label: "name" }).trim();
+ if (name === "") throw new HttpError(400, "bad_request", "name must be 1-64 characters.");
+ const minted = mintAgentApiKey();
+ const row: AgentApiKeyRow = {
+ keyId: minted.keyId,
+ projectId,
+ agentId,
+ prefix: minted.prefix,
+ name,
+ createdBy: c.var.user.userId,
+ createdAt: deps.now().toISOString(),
+ lastUsedAt: null,
+ };
+ deps.agentApi.insertKey({ ...row, tokenHash: minted.tokenHash });
+ return c.json(
+ { key: keyInfo(row), secret: minted.secret } satisfies AgentApiKeyCreateResponse,
+ 201,
+ );
+ });
+
+ app.delete("/keys/:keyId", async (c) => {
+ requireHuman(c);
+ const { projectId, agentId } = await agentOf(c, true);
+ if (!deps.agentApi.deleteKey(projectId, agentId, c.req.param("keyId"))) {
+ throw new HttpError(404, "key_not_found", "This Agent has no key with that id.");
+ }
+ return c.body(null, 204);
+ });
+
+ return app;
+}
diff --git a/packages/server/src/http/routes/agents.ts b/packages/server/src/http/routes/agents.ts
index 1bf21ddc..18303ef3 100644
--- a/packages/server/src/http/routes/agents.ts
+++ b/packages/server/src/http/routes/agents.ts
@@ -2,7 +2,8 @@
* Agent routes:
* GET|POST /api/projects/:p/agents, DELETE /:agentId (owner only).
* The list is the union of DB entries and directory scan results, including active
- * Session count, total Session count, and config last-modified time.
+ * Session count, total Session count, config last-modified time, and whether the Agent's API
+ * switch is on.
*/
import { Hono } from "hono";
import type { AgentCreateResponse, AgentsResponse, AgentSummary } from "../../api/types.js";
@@ -25,9 +26,11 @@ import type { TraceIndex } from "../../mechanisms/traces.js";
import type { ErrorLog } from "../../mechanisms/observability.js";
import type { Schedules, SessionIndex } from "../../mechanisms/sessions.js";
import type { Access } from "../../mechanisms/projects.js";
+import type { AgentApi } from "../../mechanisms/agent-api.js";
/** What this route group reaches — bound by its module (src/modules). */
export interface AgentsRouteDeps {
+ agentApi: AgentApi;
agentConfigService: AgentConfig;
agentService: AgentLifecycle;
errorsRepo: ErrorLog;
@@ -50,6 +53,8 @@ export function agentsRoutes(deps: AgentsRouteDeps): Hono<AppEnv> {
const projectId = requireValidId(c, "projectId");
deps.access.requireProjectAccess(c.var.user.userId, projectId);
const items = await deps.agentService.listAgents(projectId);
+ // One query for the whole list: which Agents have their API switch on (this server's web.db).
+ const apiEnabled = new Set(deps.agentApi.enabledAgents(projectId));
const agents: AgentSummary[] = await Promise.all(
items.map(async (item) => {
const stats = await deps.sessionService.sessionStats(
@@ -62,6 +67,7 @@ export function agentsRoutes(deps: AgentsRouteDeps): Hono<AppEnv> {
activeSessionCount: deps.manager.activeCountForAgent(projectId, item.agentId),
sessionCount: stats.sessionCount,
sessionActivity: stats.activity,
+ apiEnabled: apiEnabled.has(item.agentId),
};
}),
);
@@ -116,6 +122,8 @@ export function agentsRoutes(deps: AgentsRouteDeps): Hono<AppEnv> {
activeSessionCount: 0,
sessionCount: 0,
sessionActivity: Array.from({ length: ACTIVITY_DAYS }, () => 0),
+ // A new Agent's API is off until its owner turns it on.
+ apiEnabled: false,
};
return c.json({ agent } satisfies AgentCreateResponse, 201);
});
@@ -143,6 +151,9 @@ export function agentsRoutes(deps: AgentsRouteDeps): Hono<AppEnv> {
// are deliberately kept — historical stats survive Agent deletion (see deleteAgent).
deps.schedulesRepo.deleteByAgent(projectId, agentId);
deps.errorsRepo.deleteByAgent(projectId, agentId);
+ // The Agent's API exposure goes with it: a later Agent created under the same id starts
+ // off, and no key minted for this one opens it.
+ deps.agentApi.deleteByAgent(projectId, agentId);
} finally {
deps.manager.endAgentDeletion(projectId, agentId);
}
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index 382c6fd5..89ee2563 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -158,6 +158,7 @@ import type { UserVault } from "../../mechanisms/vault.js";
import type { Settings } from "../../mechanisms/settings.js";
import type { LiveStreams } from "../../auth/live-streams.js";
import type { Auth } from "../../mechanisms/identity.js";
+import type { AgentApi } from "../../mechanisms/agent-api.js";
/** Max title length for manual renames: looser than the auto-generated 30-char limit, to accommodate users' own organizing conventions. */
const SESSION_TITLE_MAX = 120;
@@ -1871,6 +1872,7 @@ export class SessionApiRoutes {
@Use() private readonly usage!: UsageQueries;
@Use() private readonly liveStreams!: LiveStreams;
@Use() private readonly auth!: Auth;
+ @Use() private readonly agentApi!: AgentApi;
@Bind("session-api.model-oauth-callback") modelOauthCallbackRoutes!: Hono<AppEnv>;
@Bind("session-api.models") modelsRoutes!: Hono<AppEnv>;
@Bind("session-api.model-oauth") modelOauthRoutes!: Hono<AppEnv>;
@@ -1951,6 +1953,7 @@ export class SessionApiRoutes {
});
this.commandPolicyRoutes = commandPolicyRoutes({ projectConfigService, access });
this.agentsRoutes = agentsRoutes({
+ agentApi: this.agentApi,
agentConfigService,
agentService: this.agents,
errorsRepo: this.errorsRepo,
diff --git a/packages/server/src/mechanisms/agent-api.ts b/packages/server/src/mechanisms/agent-api.ts
new file mode 100644
index 00000000..2c500920
--- /dev/null
+++ b/packages/server/src/mechanisms/agent-api.ts
@@ -0,0 +1,68 @@
+/**
+ * The Agent API mechanism: what a node may require of the per-Agent API settings and keys,
+ * declared apart from what implements it (db/repos/agent-api.ts).
+ *
+ * This server's own state, kept in web.db: never in the Agent State (the Agent must not be able
+ * to expose itself or loosen the approvals its API conversations run with) and never in the
+ * Project file (synchronized across machines in company mode, while exposure is one server's).
+ */
+import { Interface } from "@lmliheng/penguin-core/kernel";
+import type { ApprovalMode } from "../api/types.js";
+
+/** One Agent's API settings row. */
+export interface AgentApiRow {
+ projectId: string;
+ agentId: string;
+ /** The API tab's switch: off = every /api/amsp request for the Agent is 404 `agent_not_found`. */
+ enabled: boolean;
+ /** Keyless access: a request without `Authorization` is accepted; off = 401 `unauthorized`. */
+ open: boolean;
+ /** The approval mode an API Session is created with (copied onto its row, never read per decision). */
+ approvalMode: ApprovalMode;
+ updatedAt: string;
+}
+
+/** One API key as stored, minus its hash: what the list shows and what authentication resolves to. */
+export interface AgentApiKeyRow {
+ keyId: string;
+ projectId: string;
+ agentId: string;
+ /** The key's first 16 characters (`penguin_` + 8). */
+ prefix: string;
+ name: string;
+ /** user_id of whoever created it. */
+ createdBy: string;
+ createdAt: string;
+ /** Stamped once per run request that authenticated with it; null = never used. */
+ lastUsedAt: string | null;
+}
+
+/** The fields a settings write may change; omitted ones keep their stored value. */
+export interface AgentApiPatch {
+ enabled?: boolean;
+ open?: boolean;
+ approvalMode?: ApprovalMode;
+}
+
+/** AgentApi: the mechanism AgentApiRepo implements. */
+@Interface()
+export abstract class AgentApi {
+ /** The Agent's row; null = never configured, which reads as disabled, keyed, allow-all. */
+ abstract get(projectId: string, agentId: string): AgentApiRow | null;
+ /** Writes the patch over the stored row (or the defaults) and returns the row as stored. */
+ abstract set(projectId: string, agentId: string, patch: AgentApiPatch, at: string): AgentApiRow;
+ /** The Project's Agents whose switch is on, in one query (the Agent list's `apiEnabled`). */
+ abstract enabledAgents(projectId: string): string[];
+ /** The Agent's keys, oldest first. */
+ abstract listKeys(projectId: string, agentId: string): AgentApiKeyRow[];
+ abstract insertKey(row: AgentApiKeyRow & { tokenHash: string }): void;
+ /** The key whose secret hashes to `tokenHash`; null when none does. */
+ abstract findKeyByHash(tokenHash: string): AgentApiKeyRow | null;
+ abstract touchKey(keyId: string, at: string): void;
+ /** Hard delete; false when the Agent has no such key. */
+ abstract deleteKey(projectId: string, agentId: string, keyId: string): boolean;
+ /** Drops the Agent's settings and keys (the Agent was deleted). */
+ abstract deleteByAgent(projectId: string, agentId: string): void;
+ /** Drops every settings row and key of the Project (the Project was deleted). */
+ abstract deleteByProject(projectId: string): void;
+}
diff --git a/packages/server/src/mechanisms/settings.ts b/packages/server/src/mechanisms/settings.ts
index 9f08c711..cce58e0d 100644
--- a/packages/server/src/mechanisms/settings.ts
+++ b/packages/server/src/mechanisms/settings.ts
@@ -21,6 +21,8 @@ export abstract class Settings {
abstract getAttachmentLimitsMb(): { attachmentMaxMb: number; attachmentTotalMb: number };
abstract getCompanyMode(): boolean;
abstract setCompanyMode(value: boolean): void;
+ abstract getAgentApiEnabled(): boolean;
+ abstract setAgentApiEnabled(value: boolean): void;
}
/** UiPrefsStore: the mechanism UiPrefsRepo implements. */
diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.ts
index f9a06e4a..0da659d2 100644
--- a/packages/server/src/platform.ts
+++ b/packages/server/src/platform.ts
@@ -172,6 +172,7 @@ import { PreviewModule, PreviewTokens } from "./http/routes/preview.js";
import { Http, HttpModule } from "./http/app.js";
import { WebModule, WebShell } from "./http/routes/contributions.js";
import { BuiltinBrowserModule } from "./builtin-browser/module.js";
+import { AgentApiModule } from "./amsp/module.js";
/**
* The platform's module tree: the root module and its children, in one place.
@@ -502,6 +503,7 @@ export class WorkflowsModule {}
TerminalRelay,
WorkflowsModule,
BuiltinBrowserModule,
+ AgentApiModule,
Startup,
],
})
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index cc0ae61a..61938c0c 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -375,7 +375,8 @@ export function createCoreSessionLoader(
);
}
// The source this process recorded at creation, else the one the row stands for: the
- // organization runtime's are `company` (unrunSource), the list's reading of the same row.
+ // organization runtime's are `company`, the Agent API's `api` (unrunSource), the list's
+ // reading of the same row.
const knownSource = sources?.get(row.sessionId) ?? unrunSource(row.client);
try {
return await agent.createSession({
diff --git a/packages/server/src/runtime/session-sources.ts b/packages/server/src/runtime/session-sources.ts
index f6b92ccf..76d05e9a 100644
--- a/packages/server/src/runtime/session-sources.ts
+++ b/packages/server/src/runtime/session-sources.ts
@@ -44,13 +44,16 @@ export function readRecordedSource(
/**
* The source of a Session that has not run yet, read from its index row. Its session_meta is
* written by its first run, so once the process that created it is gone nothing on disk names
- * its source. The organization runtime opens only company Sessions under its `org` client (a
- * desk opened at a hire can wait days for its first run; the children its Sessions spawn run,
- * and so record their own source, at once), so such a row is `company`, and the loader rebuilds
- * it as one. Any other row stays unclassified until its first run records a source.
+ * its source. Two clients are written by the server alone, each for one source: the organization
+ * runtime opens only company Sessions under its `org` client (a desk opened at a hire can wait
+ * days for its first run; the children its Sessions spawn run, and so record their own source,
+ * at once), and the Agent API opens only `api` Sessions under its `api` client. Such a row reads
+ * as that source, and the loader rebuilds it as one. Any other row stays unclassified until its
+ * first run records a source.
*/
export function unrunSource(client: SessionRow["client"]): SessionSource | undefined {
- return client === "org" ? "company" : undefined;
+ if (client === "org") return "company";
+ return client === "api" ? "api" : undefined;
}
/**
diff --git a/packages/server/src/services/agent-routes.ts b/packages/server/src/services/agent-routes.ts
index eb4a2fdf..24b87e9b 100644
--- a/packages/server/src/services/agent-routes.ts
+++ b/packages/server/src/services/agent-routes.ts
@@ -1,19 +1,23 @@
import { Bind, Component, Use } from "@lmliheng/penguin-core/kernel";
import type { AppEnv } from "../auth/middleware.js";
import type { Hono } from "hono";
-import type { Config } from "../hmr/capabilities.js";
+import type { Clock, Config } from "../hmr/capabilities.js";
import { memoryRoutes } from "../http/routes/memory.js";
import { benchmarksRoutes } from "../http/routes/benchmarks.js";
import { agentSkillsRoutes } from "../http/routes/skills.js";
import { agentTransferRoutes } from "../http/routes/agent-transfer.js";
import { agentTracesRoutes } from "../http/routes/agent-traces.js";
+import { agentApiRoutes } from "../http/routes/agent-api.js";
+import type { AgentApi } from "../mechanisms/agent-api.js";
import type { AgentConfig, Benchmarks, Memory, Snapshots } from "../mechanisms/agents.js";
import type { Access } from "../mechanisms/projects.js";
+import type { Settings } from "../mechanisms/settings.js";
import type { Traces } from "../mechanisms/traces.js";
/**
- * The Agent-scoped route groups: memory, skills, transfer, traces — and benchmarks, which
- * are Project-level peers of an Agent but read through the same services.
+ * The Agent-scoped route groups: memory, skills, the API tab's settings and keys, transfer,
+ * traces — and benchmarks, which are Project-level peers of an Agent but read through the same
+ * services.
*/
@Component({
contributes: {
@@ -36,6 +40,12 @@ import type { Traces } from "../mechanisms/traces.js";
auth: "user",
order: 220,
},
+ {
+ id: "agents.api",
+ prefix: "/api/projects/:projectId/agents/:agentId/api",
+ auth: "user",
+ order: 225,
+ },
{
id: "agents.transfer",
prefix: "/api/projects/:projectId/agents/:agentId",
@@ -59,9 +69,13 @@ export class AgentRoutes {
@Use() private readonly snapshots!: Snapshots;
@Use() private readonly benchmarks!: Benchmarks;
@Use() private readonly traces!: Traces;
+ @Use() private readonly agentApi!: AgentApi;
+ @Use() private readonly clock!: Clock;
+ @Use() private readonly settings!: Settings;
@Bind("agents.memory") memoryRoutes!: Hono<AppEnv>;
@Bind("agents.benchmarks") benchmarksRoutes!: Hono<AppEnv>;
@Bind("agents.skills") skillsRoutes!: Hono<AppEnv>;
+ @Bind("agents.api") apiRoutes!: Hono<AppEnv>;
@Bind("agents.transfer") transferRoutes!: Hono<AppEnv>;
@Bind("agents.traces") tracesRoutes!: Hono<AppEnv>;
@@ -71,6 +85,14 @@ export class AgentRoutes {
this.memoryRoutes = memoryRoutes({ memoryService: this.memory, access });
this.benchmarksRoutes = benchmarksRoutes({ benchmarks: this.benchmarks, access });
this.skillsRoutes = agentSkillsRoutes({ agentConfigService, config: this.config, access });
+ const clock = this.clock;
+ this.apiRoutes = agentApiRoutes({
+ agentApi: this.agentApi,
+ agentConfigService,
+ access,
+ settings: this.settings,
+ now: () => clock.now(),
+ });
this.transferRoutes = agentTransferRoutes({
agentConfigService,
access,
diff --git a/packages/server/src/services/project-service.ts b/packages/server/src/services/project-service.ts
index dede9abf..161e96f9 100644
--- a/packages/server/src/services/project-service.ts
+++ b/packages/server/src/services/project-service.ts
@@ -43,6 +43,7 @@ import type { Schedules, SessionIndex } from "../mechanisms/sessions.js";
import type { ErrorLog, UsageStore } from "../mechanisms/observability.js";
import type { TraceIndex } from "../mechanisms/traces.js";
import type { OrgCache } from "../mechanisms/organization.js";
+import type { AgentApi } from "../mechanisms/agent-api.js";
/** Fallback timeout for waiting on runs to settle before deleting a Project. */
const ABORT_SETTLE_TIMEOUT_MS = 5000;
@@ -78,6 +79,8 @@ export class ProjectService implements ProjectLifecycle {
@Use() private readonly manager!: ProjectRuns;
/** Trace-index cleanup on Project destruction (rows describe files removed with the Project dir). */
@Use() private readonly traceIndex!: TraceIndex;
+ /** The Project's Agents' API settings and keys (web.db): a destroyed Project exposes nothing. */
+ @Use() private readonly agentApi!: AgentApi;
// Access control lives in ProjectAccess (services/project-access.ts); these delegate so
// in-package callers keep one entry point.
@@ -295,6 +298,9 @@ export class ProjectService implements ProjectLifecycle {
this.usage.deleteByProject(projectId);
this.errors.deleteByProject(projectId);
this.schedules.deleteByProject(projectId);
+ // Before the owner's user row can go (deleteUser destroys their Projects first): a key
+ // names its creator.
+ this.agentApi.deleteByProject(projectId);
this.orgCache.deleteProject(projectId);
this.traceIndex.removeProject(projectId);
await fs.rm(projectDir(this.root, projectId), { recursive: true, force: true });
diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.ts
index 6d62dca9..7159d526 100644
--- a/packages/server/src/services/session-service.ts
+++ b/packages/server/src/services/session-service.ts
@@ -404,7 +404,8 @@ export class SessionService {
* shard once when the file first appeared, so no file is touched here. A head that records
* no source is read with the row's client (readRecordedSource). A Session with no Trace yet
* is NOT cached — its meta appears with the first run — and reads as its row says
- * (unrunSource): the organization runtime's as `company`, any other as unknown.
+ * (unrunSource): the organization runtime's as `company`, the Agent API's as `api`, any other
+ * as unknown.
*/
private async sourceOf(row: SessionRow, hasTrace: boolean): Promise<SessionSource | undefined> {
const known = this.deps.sources.get(row.sessionId);
@@ -660,16 +661,18 @@ export class SessionService {
/**
* What kind of conversation this is, recorded in the Session's session_meta: `schedule`
* from the scheduler, `company` from the organization runtime, `cli` from `penguin run`
- * (the only source a request may name); absent means `user`, a person's conversation.
+ * (the only source a request may name), `api` from an Agent API run; absent means `user`,
+ * a person's conversation.
*/
source?: SessionSource;
/**
* Creating-client hint stored on the index row (`POST .../sessions` body `client`):
- * "cli" from the CLI, defaulting to "web". "org" is not accepted over HTTP — the
- * organization runtime calls this method directly and is the only caller that passes
- * it, so no request can claim an organization's provenance for itself.
+ * "cli" from the CLI, defaulting to "web". "org" and "api" are not accepted over HTTP —
+ * the organization runtime and the Agent API's run handler call this method directly and
+ * are the only callers that pass them, so no request can claim either provenance for
+ * itself ("api" is what lets the Agent API continue a Session).
*/
- client?: "web" | "cli" | "org";
+ client?: "web" | "cli" | "org" | "api";
}): Promise<SessionInfo> {
if ((args.modelId === undefined) !== (args.provider === undefined)) {
throw badRequest(
@@ -746,8 +749,9 @@ export class SessionService {
sandbox,
title: null,
// The creator's hint: "cli" when the CLI created this Session through the API,
- // "org" when the organization runtime opened a desk or a ticket session, otherwise
- // "web" (schedule runs included). NULL means a legacy row, treated as web.
+ // "org" when the organization runtime opened a desk or a ticket session, "api" when an
+ // Agent API run did, otherwise "web" (schedule runs included). NULL means a legacy row,
+ // treated as web.
client: args.client ?? "web",
// Creation is the first activity; the first driven run advances it (see SessionManager.drive).
lastActiveAt: createdAt,
diff --git a/packages/server/test/agent-api-settings.test.ts b/packages/server/test/agent-api-settings.test.ts
new file mode 100644
index 00000000..ee7ce943
--- /dev/null
+++ b/packages/server/test/agent-api-settings.test.ts
@@ -0,0 +1,334 @@
+/**
+ * The Agent API's management surface: the API tab's routes
+ * (`/api/projects/:projectId/agents/:agentId/api`), the Agent list's mark, the deletion
+ * cascades, and the admin's switch.
+ *
+ * Scenarios:
+ * - Given a Project member, the settings read back (off, keyed, allow-all, no keys for an Agent
+ * never configured); changing them — the switch, keyless access, the approval mode, a key —
+ * is the owner's alone, and a PUT with one invalid field changes nothing.
+ * - Given a created key, its secret is in the create response only: the listing shows its
+ * prefix, name, creator and when it was last used — stamped by a run that authenticated
+ * with it — and never the secret; a name outside 1-64 characters is refused, and deleting a
+ * key the Agent does not have is 404.
+ * - Given the Agent list, only the Agent whose switch is on carries the API mark, and a newly
+ * created Agent carries none.
+ * - Given an exposed Agent deleted and created again under the same id, it starts off with no
+ * keys, and the old key opens nothing.
+ * - Given a Project with keys whose owner is deleted, the deletion goes through.
+ * - Given the admin, the Agent API switch reads on by default and round-trips through
+ * GET/PUT /api/admin/settings; a non-admin cannot change it.
+ * - Given the admin's switch off, a Project owner who cannot read the admin settings learns it
+ * from the API tab's settings, on a read and on a write alike.
+ * - Given the local API token, the credential every tool subprocess holds: it reads an Agent's
+ * settings and keys, but turning the API on, creating a key, deleting one and Try it are each
+ * 403 `human_required` and change nothing, run nothing and create no Session; the owner's
+ * sign-in then does each of them.
+ * - Given the local API token on the admin settings: it changes every setting but
+ * `agentApiEnabled`; a body carrying that is 403 `human_required` alone, and none of its
+ * other fields is written.
+ */
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import type {
+ AgentApiKeyCreateResponse,
+ AgentApiResponse,
+ AgentsResponse,
+ ServerSettingsResponse,
+} from "../src/api/types.js";
+import { apiClient, createTestApp, loginAdmin, provisionUser, tokenClient } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+import { adoptSession, fakeSession, uniqueSessionId } from "./fixtures/session.js";
+
+type Client = ReturnType<typeof apiClient>;
+
+describe("Agent API settings", () => {
+ let t: TestApp;
+ let admin: Client;
+ let owner: Client;
+ let member: Client;
+ let projectId: string;
+ const tab = (agentId: string) => `/api/projects/${projectId}/agents/${agentId}/api`;
+ const read = async (client: Client, agentId: string) =>
+ ((await (await client.get(tab(agentId))).json()) as AgentApiResponse).api;
+
+ beforeAll(async () => {
+ t = await createTestApp();
+ admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);
+ owner = apiClient(t.app, (await provisionUser(t.app, "api_owner")).cookie);
+ member = apiClient(t.app, (await provisionUser(t.app, "api_member")).cookie);
+ projectId = "api_owner-default_project";
+ expect(
+ (await owner.post(`/api/projects/${projectId}/members`, { userId: "api_member" })).status,
+ ).toBe(201);
+ for (const agentId of ["keyed_agent", "quiet_agent"]) {
+ expect((await owner.post(`/api/projects/${projectId}/agents`, { agentId })).status).toBe(201);
+ }
+ });
+ afterAll(async () => {
+ await t.deps.manager.shutdown();
+ await t.cleanup();
+ });
+
+ it("a member reads the settings, only the owner changes them (enabled, open, approval mode)", async () => {
+ expect(await read(member, "default_agent")).toEqual({
+ enabled: false,
+ open: false,
+ approvalMode: "allow-all",
+ keys: [],
+ });
+ for (const res of [
+ await member.put(tab("default_agent"), { enabled: true }),
+ await member.post(`${tab("default_agent")}/keys`, { name: "mine" }),
+ ]) {
+ expect(res.status).toBe(403);
+ }
+ const put = await owner.put(tab("default_agent"), {
+ enabled: true,
+ open: true,
+ approvalMode: "read-only",
+ });
+ expect(put.status).toBe(200);
+ expect(((await put.json()) as AgentApiResponse).api).toMatchObject({
+ enabled: true,
+ open: true,
+ approvalMode: "read-only",
+ });
+ // One invalid field and nothing is written.
+ const bad = await owner.put(tab("default_agent"), {
+ enabled: false,
+ approvalMode: "sometimes",
+ });
+ expect(bad.status).toBe(400);
+ expect(await read(member, "default_agent")).toMatchObject({
+ enabled: true,
+ open: true,
+ approvalMode: "read-only",
+ });
+ // Omitted fields keep their value.
+ await owner.put(tab("default_agent"), { open: false });
+ expect(await read(owner, "default_agent")).toMatchObject({ enabled: true, open: false });
+ // Someone outside the Project learns nothing.
+ const stranger = apiClient(t.app, (await provisionUser(t.app, "api_stranger")).cookie);
+ expect((await stranger.get(tab("default_agent"))).status).toBe(404);
+ // An Agent that does not exist has no settings to read.
+ expect((await owner.get(tab("ghost_agent"))).status).toBe(404);
+ });
+
+ it("creating a key returns the secret once; the listing shows the prefix and never the secret", async () => {
+ await owner.put(tab("keyed_agent"), { enabled: true });
+ const res = await owner.post(`${tab("keyed_agent")}/keys`, { name: "ci runner" });
+ expect(res.status).toBe(201);
+ const { key, secret } = (await res.json()) as AgentApiKeyCreateResponse;
+ expect(secret).toMatch(/^penguin_[A-Za-z0-9_-]{43}$/);
+ expect(key).toMatchObject({
+ name: "ci runner",
+ prefix: secret.slice(0, 16),
+ createdBy: "api_owner",
+ lastUsedAt: null,
+ });
+ const listing = await member.get(tab("keyed_agent"));
+ const text = await listing.text();
+ expect(text).not.toContain(secret);
+ expect((JSON.parse(text) as AgentApiResponse).api.keys).toEqual([key]);
+
+ // A run that authenticated with the key stamps it.
+ const sessionId = uniqueSessionId();
+ adoptSession(t.deps, fakeSession(sessionId), {
+ projectId,
+ agentId: "keyed_agent",
+ client: "api",
+ });
+ const run = await t.app.request(`/api/amsp/v1/agents/${projectId}/keyed_agent/runs`, {
+ method: "POST",
+ headers: { authorization: `Bearer ${secret}`, "content-type": "application/json" },
+ body: JSON.stringify({ session_id: sessionId, input: "hi" }),
+ });
+ expect(run.status).toBe(200);
+ await run.text();
+ const [used] = (await read(owner, "keyed_agent")).keys;
+ expect(Number.isNaN(Date.parse(used!.lastUsedAt ?? ""))).toBe(false);
+
+ for (const name of ["", " ", "x".repeat(65)]) {
+ expect((await owner.post(`${tab("keyed_agent")}/keys`, { name })).status).toBe(400);
+ }
+ const missing = await owner.delete(`${tab("keyed_agent")}/keys/not-a-key`);
+ expect(missing.status).toBe(404);
+ expect(((await missing.json()) as { error: { code: string } }).error.code).toBe(
+ "key_not_found",
+ );
+ expect((await read(owner, "keyed_agent")).keys).toHaveLength(1);
+ });
+
+ it("the Agent list marks an enabled Agent and nothing else", async () => {
+ await owner.put(tab("quiet_agent"), { enabled: true });
+ await owner.put(tab("quiet_agent"), { enabled: false });
+ const created = await owner.post(`/api/projects/${projectId}/agents`, { agentId: "fresh_one" });
+ expect(((await created.json()) as { agent: { apiEnabled: boolean } }).agent.apiEnabled).toBe(
+ false,
+ );
+ const { agents } = (await (
+ await member.get(`/api/projects/${projectId}/agents`)
+ ).json()) as AgentsResponse;
+ const marked = Object.fromEntries(agents.map((a) => [a.agentId, a.apiEnabled]));
+ expect(marked).toMatchObject({
+ default_agent: true,
+ keyed_agent: true,
+ quiet_agent: false,
+ fresh_one: false,
+ });
+ });
+
+ it("deleting the Agent removes its switch and keys", async () => {
+ await owner.post(`/api/projects/${projectId}/agents`, { agentId: "short_lived" });
+ await owner.put(tab("short_lived"), { enabled: true, open: true, approvalMode: "deny-all" });
+ const { secret } = (await (
+ await owner.post(`${tab("short_lived")}/keys`, { name: "k" })
+ ).json()) as AgentApiKeyCreateResponse;
+ expect((await owner.delete(`/api/projects/${projectId}/agents/short_lived`)).status).toBe(204);
+
+ await owner.post(`/api/projects/${projectId}/agents`, { agentId: "short_lived" });
+ expect(await read(owner, "short_lived")).toEqual({
+ enabled: false,
+ open: false,
+ approvalMode: "allow-all",
+ keys: [],
+ });
+ await owner.put(tab("short_lived"), { enabled: true });
+ const old = await t.app.request(`/api/amsp/v1/agents/${projectId}/short_lived`, {
+ headers: { authorization: `Bearer ${secret}` },
+ });
+ expect(old.status).toBe(401);
+ });
+
+ it("a Project's switches and keys go with it, so its owner's account can be deleted", async () => {
+ const doomed = apiClient(t.app, (await provisionUser(t.app, "api_doomed")).cookie);
+ const base = `/api/projects/api_doomed-default_project/agents/default_agent/api`;
+ expect((await doomed.put(base, { enabled: true })).status).toBe(200);
+ expect((await doomed.post(`${base}/keys`, { name: "k" })).status).toBe(201);
+ expect((await admin.delete("/api/admin/users/api_doomed")).status).toBe(204);
+ expect(
+ t.deps.db
+ .prepare("SELECT COUNT(*) AS n FROM agent_api_keys WHERE project_id = ?")
+ .get("api_doomed-default_project"),
+ ).toEqual({ n: 0 });
+ });
+
+ it("the API tab tells an owner who is no admin that the admin has the API off", async () => {
+ expect((await owner.get("/api/admin/settings")).status).toBe(403);
+ expect(
+ ((await (await owner.get(tab("default_agent"))).json()) as AgentApiResponse).serverEnabled,
+ ).toBe(true);
+ await admin.put("/api/admin/settings", { agentApiEnabled: false });
+ try {
+ const read = (await (await member.get(tab("default_agent"))).json()) as AgentApiResponse;
+ expect(read.serverEnabled).toBe(false);
+ // The Agent's own switch is kept, and a write answers the same way.
+ expect(read.api.enabled).toBe(true);
+ const write = await owner.put(tab("default_agent"), { open: false });
+ expect(((await write.json()) as AgentApiResponse).serverEnabled).toBe(false);
+ } finally {
+ await admin.put("/api/admin/settings", { agentApiEnabled: true });
+ }
+ });
+
+ /** The answer is a refusal for want of a person's sign-in. */
+ const humanRequired = async (res: Response) => {
+ expect(res.status).toBe(403);
+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe("human_required");
+ };
+
+ it("the local API token reads an Agent's API but cannot change it or try it; the owner's sign-in can", async () => {
+ // The admin's own Project: the token authenticates as the admin, who owns it.
+ const mine = "/api/projects/default_project/agents/default_agent/api";
+ const token = tokenClient(t.app, t.deps.authService.localApiToken()!);
+ const readByToken = async () => {
+ const res = await token.get(mine);
+ expect(res.status).toBe(200);
+ return ((await res.json()) as AgentApiResponse).api;
+ };
+
+ await humanRequired(await token.put(mine, { enabled: true, open: true }));
+ expect(await readByToken()).toMatchObject({ enabled: false, open: false });
+ expect((await admin.put(mine, { enabled: true })).status).toBe(200);
+ expect(await readByToken()).toMatchObject({ enabled: true, open: false });
+
+ await humanRequired(await token.post(`${mine}/keys`, { name: "carried out" }));
+ expect((await readByToken()).keys).toEqual([]);
+ const created = await admin.post(`${mine}/keys`, { name: "ci" });
+ expect(created.status).toBe(201);
+ const { key } = (await created.json()) as AgentApiKeyCreateResponse;
+ expect((await readByToken()).keys).toEqual([key]);
+
+ await humanRequired(await token.delete(`${mine}/keys/${key.keyId}`));
+ expect((await readByToken()).keys).toEqual([key]);
+ expect((await admin.delete(`${mine}/keys/${key.keyId}`)).status).toBe(204);
+ expect((await readByToken()).keys).toEqual([]);
+
+ // Try it: refused before anything runs or is created, on a new conversation and an old one.
+ let runs = 0;
+ const sessionId = uniqueSessionId();
+ adoptSession(
+ t.deps,
+ fakeSession(sessionId, {
+ async *run() {
+ runs += 1;
+ },
+ }),
+ { projectId: "default_project", agentId: "default_agent", client: "api" },
+ );
+ const sessions = t.deps.sessionsRepo.listByAgent("default_project", "default_agent").length;
+ await humanRequired(await token.post(`${mine}/try`, { input: "hi" }));
+ await humanRequired(await token.post(`${mine}/try`, { session_id: sessionId, input: "hi" }));
+ expect(runs).toBe(0);
+ expect(t.deps.sessionsRepo.listByAgent("default_project", "default_agent")).toHaveLength(
+ sessions,
+ );
+ const tried = await admin.post(`${mine}/try`, { session_id: sessionId, input: "hi" });
+ expect(tried.status).toBe(200);
+ await tried.text();
+ expect(runs).toBe(1);
+ });
+
+ it("the local API token changes every admin setting but agentApiEnabled, which is refused with the rest of its body", async () => {
+ const token = tokenClient(t.app, t.deps.authService.localApiToken()!);
+ const read = async () =>
+ ((await (await token.get("/api/admin/settings")).json()) as ServerSettingsResponse).settings;
+ const before = await read();
+ const flipped = {
+ proxyForApp: !before.proxyForApp,
+ proxyForAgent: !before.proxyForAgent,
+ };
+ try {
+ expect((await token.put("/api/admin/settings", flipped)).status).toBe(200);
+ expect(await read()).toEqual({ ...before, ...flipped });
+
+ await humanRequired(
+ await token.put("/api/admin/settings", {
+ agentApiEnabled: !before.agentApiEnabled,
+ proxyForAgent: before.proxyForAgent,
+ proxyForApp: before.proxyForApp,
+ }),
+ );
+ expect(await read()).toEqual({ ...before, ...flipped });
+ } finally {
+ await token.put("/api/admin/settings", {
+ proxyForAgent: before.proxyForAgent,
+ proxyForApp: before.proxyForApp,
+ });
+ }
+ });
+
+ it("the admin switch round-trips through GET/PUT /api/admin/settings", async () => {
+ const get = async () =>
+ ((await (await admin.get("/api/admin/settings")).json()) as ServerSettingsResponse).settings;
+ expect((await get()).agentApiEnabled).toBe(true);
+ const off = await admin.put("/api/admin/settings", { agentApiEnabled: false });
+ expect(((await off.json()) as ServerSettingsResponse).settings.agentApiEnabled).toBe(false);
+ expect((await get()).agentApiEnabled).toBe(false);
+ expect((await admin.put("/api/admin/settings", { agentApiEnabled: "no" })).status).toBe(400);
+ expect((await owner.put("/api/admin/settings", { agentApiEnabled: true })).status).toBe(403);
+ expect((await get()).agentApiEnabled).toBe(false);
+ await admin.put("/api/admin/settings", { agentApiEnabled: true });
+ expect((await get()).agentApiEnabled).toBe(true);
+ });
+});
diff --git a/packages/server/test/amsp-routes.test.ts b/packages/server/test/amsp-routes.test.ts
new file mode 100644
index 00000000..268b4656
--- /dev/null
+++ b/packages/server/test/amsp-routes.test.ts
@@ -0,0 +1,1095 @@
+/**
+ * The Agent API on the wire: the real Hono app, requests in, response bytes out, read the way a
+ * client reads them (the client package's `readSse` over the body). Sessions are fake runtimes adopted as API
+ * Sessions (fixtures/session.ts) playing scripted streams, except where creating a Session is
+ * the point: those run a real core Session against a loopback model (live-session.ts).
+ *
+ * Scenarios — the gate:
+ * - Given a keyed Agent, a run without a key is refused 401 before its body is read (a body
+ * that is not even JSON gets the 401), and nothing is created.
+ * - Given a wrong key, the answer is 401; a key deleted on the API tab is refused from the next
+ * request on.
+ * - Given another Agent's key, the answer is the 404 an unknown Agent gets, body for body.
+ * - Given an Agent whose API switch is off, existing or not, the answer is that same 404.
+ * - Given the admin switch off, every route answers 403 `agent_api_disabled` but the preflight.
+ * - Given an Agent that allows keyless access, a keyless run streams and carries no
+ * Access-Control-Allow-Origin; with keyless access off it is 401.
+ * - Given a key, every response carries Access-Control-Allow-Origin *, errors included; a
+ * preflight is answered without one.
+ * - Given a body the server-wide checks refuse before the group is reached (over the body cap:
+ * 413; not JSON: 415), a keyed request still carries Access-Control-Allow-Origin *, so a
+ * browser reads the code rather than a CORS failure; a keyless one carries none.
+ * - Given an unknown path under the prefix, the answer is a JSON 404 — not the SPA, not a 401.
+ *
+ * Scenarios — runs:
+ * - Given a run without session_id, a Session is created with client `api` and source `api`
+ * and run.started names it; the stream is the real Session's projected — its toolset, one
+ * Request answering, run.done completed — and does not echo the input.
+ * - Given the Agent's API approval mode, the Session a run creates carries it; changing the
+ * mode on the tab leaves that Session as it was, and a PATCH on the Session moves it.
+ * - Given a run with session_id, the same Session continues and its runtime receives the new
+ * input only, texts before images, none of it streamed back.
+ * - Given a Session the Web App created, or another Agent's API Session, the answer is 404
+ * `session_not_found`.
+ * - Given a busy Session, a second run is 409 and nothing is streamed.
+ * - Given a Session whose Trace is gone, so that loading it heals it into a new id, the run is
+ * followed there: run.started names the new id and the stream runs to its end.
+ * - Given an Agent with four runs going, a fifth is 429 with Retry-After, and creates nothing.
+ * - Given each scripted stream, the caller reads exactly the fixture's events, ending with one
+ * run.done and then [DONE] (the approval script answered through the approvals route, which
+ * has nothing left to decide afterwards).
+ * - Given the Web App's approval card answering first, the run goes on and the caller's answer
+ * finds nothing pending.
+ * - Given a caller that disconnects mid-run, the run is aborted.
+ * - Given an explicit abort, the stream ends with run.done aborted; aborting an idle Session is
+ * a 204.
+ * - Given a malformed body, the answer is 400 `bad_request` naming the field — an oversized or
+ * non-image data URL, a file item, too many image bytes included — and nothing is created.
+ * - Given 15 s of silence, a `: keep-alive` comment is written (fake timers).
+ * - Given a failure of the server's own while driving, the stream ends with run.done fatal
+ * `internal` and [DONE], and the run is stopped.
+ *
+ * Scenarios — the API tab's try route (`POST /api/projects/:p/agents/:a/api/try`, the owner's
+ * sign-in in place of a key):
+ * - Given the owner's cookie, the try route streams what a keyed run streams, event type for
+ * event type: run.started names a Session with client `api`, source `api` and the Agent's API
+ * approval mode, then run.done and [DONE]; no key's last use moves.
+ * - Given a member who is not the owner, the answer is 403 `owner_required`; a user outside the
+ * Project gets 404, a signed-out request 401; none of them creates anything.
+ * - Given the Agent's switch off, or no such Agent, the answer is 404 `agent_not_found`; given
+ * the admin's switch off, 403 `agent_api_disabled` — the public routes' own refusals.
+ * - Given a session_id, an API Session of the Agent continues; a web Session's id is 404
+ * `session_not_found`.
+ * - Given four runs of the Agent going through the try route, a fifth is 429 there and on the
+ * public route alike.
+ * - Given a malformed body, the answer is the public route's 400 `bad_request`, byte for byte.
+ * - Given a caller that disconnects from the try stream, the run is aborted.
+ */
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import {
+ abortEvent,
+ assistantText,
+ partialText,
+ requestBegin,
+ requestEnd,
+} from "@lmliheng/penguin-core";
+import type { OmniMessage, ToolCallPayload } from "@lmliheng/penguin-core";
+import { readSse } from "@lmliheng/amsp";
+import type { AmspEvent } from "@lmliheng/amsp";
+import type {
+ AgentApiKeyCreateResponse,
+ AgentApiResponse,
+ ApprovalMode,
+ SessionResponse,
+} from "../src/api/types.js";
+import type { RuntimeSession, SessionLoader } from "../src/runtime/session-manager.js";
+import { bodyLimitBytes } from "../src/services/attachment-limits.js";
+import { apiClient, createTestApp, loginAdmin, provisionUser, waitFor } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+import { adoptSession, fakeSession, sessionRow, uniqueSessionId } from "./fixtures/session.js";
+import {
+ AMSP_FIXTURE_NOW,
+ AMSP_STREAM_SCRIPTS,
+ APPROVAL_ROUND_TRIP,
+} from "./fixtures/amsp-stream.js";
+import type { AmspStreamScript } from "./fixtures/amsp-stream.js";
+import { MOCK_MODEL_ID, startMockLLM } from "./live-session.js";
+import type { MockLLM } from "./live-session.js";
+
+const P = "default_project";
+const A = "default_agent";
+const PREFIX = "/api/amsp/v1";
+
+type Admin = ReturnType<typeof apiClient>;
+
+/** One request to the public group: a key when given, a JSON body when given. */
+async function amsp(
+ t: TestApp,
+ path: string,
+ init: { method?: string; key?: string; body?: unknown; raw?: string } = {},
+): Promise<Response> {
+ const hasBody = init.body !== undefined || init.raw !== undefined;
+ return await t.app.request(`${PREFIX}${path}`, {
+ method: init.method ?? (hasBody ? "POST" : "GET"),
+ headers: {
+ ...(init.key !== undefined ? { authorization: `Bearer ${init.key}` } : {}),
+ ...(hasBody ? { "content-type": "application/json" } : {}),
+ },
+ ...(hasBody ? { body: init.raw ?? JSON.stringify(init.body) } : {}),
+ });
+}
+
+/** A response body read event by event, as a client reads it. */
+function stream(res: Response) {
+ const body = res.body!;
+ const reader = readSse(body);
+ return {
+ /** The next `data:` payload, parsed; "[DONE]" as the string; undefined once the body ends. */
+ async next(): Promise<AmspEvent | "[DONE]" | undefined> {
+ const r = await reader.next();
+ if (r.done) return undefined;
+ return r.value === "[DONE]" ? "[DONE]" : (JSON.parse(r.value) as AmspEvent);
+ },
+ /** Events up to and including the first of `type`. */
+ async until(type: AmspEvent["type"]): Promise<AmspEvent[]> {
+ const out: AmspEvent[] = [];
+ for (;;) {
+ const item = await this.next();
+ if (item === undefined || item === "[DONE]") throw new Error(`no ${type} before the end`);
+ out.push(item);
+ if (item.type === type) return out;
+ }
+ },
+ /** Everything left, to the end of the body. */
+ async rest(): Promise<Array<AmspEvent | "[DONE]">> {
+ const out: Array<AmspEvent | "[DONE]"> = [];
+ for (let item = await this.next(); item !== undefined; item = await this.next()) {
+ out.push(item);
+ }
+ return out;
+ },
+ /** The caller goes away: a reader that has started cancels the body as it stops. */
+ async disconnect(): Promise<void> {
+ await reader.return(undefined);
+ if (!body.locked) await body.cancel();
+ },
+ };
+}
+
+/** The events with every server-stamped `at` checked and pinned, so they compare to a fixture. */
+function pinned(events: Array<AmspEvent | "[DONE]">): Array<AmspEvent | "[DONE]"> {
+ return events.map((e) => {
+ if (e === "[DONE]") return e;
+ if (e.type === "run.started" || e.type === "run.done" || e.type === "approval.requested") {
+ expect(Number.isNaN(Date.parse(e.at))).toBe(false);
+ return { ...e, at: AMSP_FIXTURE_NOW };
+ }
+ return e;
+ });
+}
+
+/**
+ * A runtime that starts a request, then waits — for `release()` or an abort — and records what
+ * each run was given and whether it was aborted.
+ */
+function blocking(sessionId: string) {
+ let release: () => void = () => {};
+ const runs: Array<{ input: OmniMessage[]; signal: AbortSignal }> = [];
+ const session = fakeSession(sessionId, {
+ async *run(input, { signal }) {
+ runs.push({ input, signal });
+ const released = new Promise<void>((resolve) => (release = resolve));
+ yield requestBegin();
+ yield partialText("start");
+ yield partialText("delta", "Working");
+ await Promise.race([
+ released,
+ new Promise<void>((resolve) => signal.addEventListener("abort", () => resolve())),
+ ]);
+ if (signal.aborted) {
+ yield requestEnd("aborted", { attempt: 1 });
+ yield abortEvent("user_abort");
+ return;
+ }
+ yield assistantText("Working");
+ yield requestEnd("completed");
+ },
+ });
+ return { session, runs, release: () => release() };
+}
+
+/** A runtime that plays a script, asking for approval where the script does. */
+function scripted(script: AmspStreamScript, decisions: string[] = []): RuntimeSession {
+ return fakeSession(script.sessionId, {
+ async *run(_input, { approve }) {
+ for (const step of script.steps) {
+ if ("approve" in step) {
+ const call: OmniMessage<ToolCallPayload> = {
+ timestamp: AMSP_FIXTURE_NOW,
+ type: "model_msg",
+ payload: {
+ type: "tool_call",
+ role: "assistant",
+ ...step.approve,
+ stop_reason: "completed",
+ },
+ };
+ decisions.push(await approve(call));
+ } else {
+ yield step.message as unknown as OmniMessage;
+ }
+ }
+ },
+ });
+}
+
+/** Turns an Agent's API on and mints a key for it; returns the key. */
+async function expose(admin: Admin, agentId: string, settings: object = {}): Promise<string> {
+ const base = `/api/projects/${P}/agents/${agentId}/api`;
+ expect((await admin.put(base, { enabled: true, ...settings })).status).toBe(200);
+ const res = await admin.post(`${base}/keys`, { name: `${agentId} suite` });
+ expect(res.status).toBe(201);
+ return ((await res.json()) as AgentApiKeyCreateResponse).secret;
+}
+
+async function createAgent(admin: Admin, agentId: string): Promise<void> {
+ expect((await admin.post(`/api/projects/${P}/agents`, { agentId })).status).toBe(201);
+}
+
+async function errorOf(res: Response): Promise<{ status: number; code: string; body: string }> {
+ const body = await res.text();
+ return {
+ status: res.status,
+ code: (JSON.parse(body) as { error: { code: string } }).error.code,
+ body,
+ };
+}
+
+describe("Agent API: the gate", () => {
+ let t: TestApp;
+ let admin: Admin;
+ let key: string;
+ let otherKey: string;
+
+ beforeAll(async () => {
+ t = await createTestApp();
+ admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);
+ key = await expose(admin, A);
+ await createAgent(admin, "other_agent");
+ otherKey = await expose(admin, "other_agent");
+ await createAgent(admin, "dark_agent");
+ });
+ afterAll(async () => {
+ await t.deps.manager.shutdown();
+ await t.cleanup();
+ });
+
+ it("a run without a key on a keyed Agent is refused 401 before the body is read", async () => {
+ const before = t.deps.sessionsRepo.listByAgent(P, A).length;
+ const res = await amsp(t, `/agents/${P}/${A}/runs`, { raw: "{not json" });
+ expect(await errorOf(res)).toMatchObject({ status: 401, code: "unauthorized" });
+ expect(t.deps.sessionsRepo.listByAgent(P, A)).toHaveLength(before);
+ });
+
+ it("a wrong key is 401, and a deleted key is 401 from the next request on", async () => {
+ expect((await amsp(t, `/agents/${P}/${A}`, { key: "test-agent-key" })).status).toBe(401);
+ const created = (await (
+ await admin.post(`/api/projects/${P}/agents/${A}/api/keys`, { name: "short-lived" })
+ ).json()) as AgentApiKeyCreateResponse;
+ expect((await amsp(t, `/agents/${P}/${A}`, { key: created.secret })).status).toBe(200);
+ expect(
+ (await admin.delete(`/api/projects/${P}/agents/${A}/api/keys/${created.key.keyId}`)).status,
+ ).toBe(204);
+ expect(
+ await errorOf(await amsp(t, `/agents/${P}/${A}`, { key: created.secret })),
+ ).toMatchObject({ status: 401, code: "unauthorized" });
+ });
+
+ it("a key of another Agent is 404 agent_not_found, the same body as for an unknown Agent", async () => {
+ const theirs = await errorOf(await amsp(t, `/agents/${P}/${A}`, { key: otherKey }));
+ const unknown = await errorOf(await amsp(t, `/agents/${P}/no_such_agent`, { key }));
+ expect(theirs).toMatchObject({ status: 404, code: "agent_not_found" });
+ expect(theirs.body).toBe(unknown.body);
+ // The same key opens its own Agent.
+ const own = await amsp(t, `/agents/${P}/other_agent`, { key: otherKey });
+ expect(own.status).toBe(200);
+ expect(await own.json()).toMatchObject({ agent: { id: `${P}/other_agent` } });
+ });
+
+ it("an Agent whose switch is off is 404 whether or not it exists", async () => {
+ const dark = await errorOf(
+ await amsp(t, `/agents/${P}/dark_agent/runs`, { body: { input: "hi" } }),
+ );
+ const ghost = await errorOf(await amsp(t, `/agents/${P}/ghost_agent`));
+ const badId = await errorOf(await amsp(t, `/agents/${P}/..%2Fescape`));
+ expect(dark).toMatchObject({ status: 404, code: "agent_not_found" });
+ expect(ghost.body).toBe(dark.body);
+ expect(badId.body).toBe(dark.body);
+ // Switching it off again takes an exposed Agent back out of reach.
+ await admin.put(`/api/projects/${P}/agents/other_agent/api`, { enabled: false });
+ try {
+ expect(
+ (await errorOf(await amsp(t, `/agents/${P}/other_agent`, { key: otherKey }))).body,
+ ).toBe(dark.body);
+ } finally {
+ await admin.put(`/api/projects/${P}/agents/other_agent/api`, { enabled: true });
+ }
+ });
+
+ it("the admin switch off answers 403 to every route but preflight", async () => {
+ const sessionId = uniqueSessionId();
+ adoptSession(t.deps, fakeSession(sessionId), { projectId: P, agentId: A, client: "api" });
+ expect((await admin.put("/api/admin/settings", { agentApiEnabled: false })).status).toBe(200);
+ try {
+ const refused = [
+ amsp(t, `/agents/${P}/${A}`, { key }),
+ amsp(t, `/agents/${P}/${A}/runs`, { key, body: { input: "hi" } }),
+ amsp(t, `/sessions/${sessionId}`, { key }),
+ amsp(t, `/sessions/${sessionId}/abort`, { key, method: "POST" }),
+ amsp(t, `/sessions/${sessionId}/approvals/call_1`, { key, body: { decision: "allow" } }),
+ amsp(t, `/no/such/route`),
+ ];
+ for (const res of await Promise.all(refused)) {
+ expect(await errorOf(res)).toMatchObject({ status: 403, code: "agent_api_disabled" });
+ }
+ const preflight = await amsp(t, `/agents/${P}/${A}/runs`, { method: "OPTIONS" });
+ expect(preflight.status).toBe(204);
+ } finally {
+ await admin.put("/api/admin/settings", { agentApiEnabled: true });
+ }
+ expect((await amsp(t, `/sessions/${sessionId}`, { key })).status).toBe(200);
+ });
+
+ it("an open Agent accepts a keyless run and sends no Access-Control-Allow-Origin", async () => {
+ const sessionId = uniqueSessionId();
+ const { session, release } = blocking(sessionId);
+ adoptSession(t.deps, session, { projectId: P, agentId: A, client: "api" });
+ await admin.put(`/api/projects/${P}/agents/${A}/api`, { open: true });
+ try {
+ const res = await amsp(t, `/agents/${P}/${A}/runs`, {
+ body: { session_id: sessionId, input: "no key" },
+ });
+ expect(res.status).toBe(200);
+ expect(res.headers.get("access-control-allow-origin")).toBeNull();
+ const events = stream(res);
+ await events.until("text.delta");
+ release();
+ expect((await events.rest()).at(-1)).toBe("[DONE]");
+ } finally {
+ await admin.put(`/api/projects/${P}/agents/${A}/api`, { open: false });
+ }
+ const closed = await amsp(t, `/agents/${P}/${A}/runs`, {
+ body: { session_id: sessionId, input: "no key" },
+ });
+ expect(await errorOf(closed)).toMatchObject({ status: 401, code: "unauthorized" });
+ });
+
+ it("a keyed response carries Access-Control-Allow-Origin * and preflight is answered without a key", async () => {
+ const ok = await amsp(t, `/agents/${P}/${A}`, { key });
+ expect(ok.headers.get("access-control-allow-origin")).toBe("*");
+ const refused = await amsp(t, `/sessions/${uniqueSessionId()}`, { key });
+ expect(refused.status).toBe(404);
+ expect(refused.headers.get("access-control-allow-origin")).toBe("*");
+
+ const sessionId = uniqueSessionId();
+ const { session, release } = blocking(sessionId);
+ adoptSession(t.deps, session, { projectId: P, agentId: A, client: "api" });
+ const streamed = await amsp(t, `/agents/${P}/${A}/runs`, {
+ key,
+ body: { session_id: sessionId, input: "hi" },
+ });
+ expect(streamed.headers.get("access-control-allow-origin")).toBe("*");
+ release();
+ await stream(streamed).rest();
+
+ const preflight = await amsp(t, `/agents/${P}/${A}/runs`, { method: "OPTIONS" });
+ expect(preflight.status).toBe(204);
+ expect(preflight.headers.get("access-control-allow-origin")).toBe("*");
+ expect(preflight.headers.get("access-control-allow-methods")).toBe("GET, POST, OPTIONS");
+ expect(preflight.headers.get("access-control-allow-headers")).toBe(
+ "Authorization, Content-Type",
+ );
+ expect(preflight.headers.get("access-control-max-age")).toBe("600");
+ });
+
+ it("a keyed request the server-wide body checks refuse still carries Access-Control-Allow-Origin *", async () => {
+ const cap = bodyLimitBytes(t.deps.serverSettingsRepo.getAttachmentLimitsMb());
+ const oversized = (headers: Record<string, string>) =>
+ t.app.request(`${PREFIX}/agents/${P}/${A}/runs`, {
+ method: "POST",
+ headers: { ...headers, "content-type": "application/json", "content-length": `${cap + 1}` },
+ body: JSON.stringify({ input: "small" }),
+ });
+ const notJson = (headers: Record<string, string>) =>
+ t.app.request(`${PREFIX}/agents/${P}/${A}/runs`, {
+ method: "POST",
+ headers: { ...headers, "content-type": "text/plain" },
+ body: "hello",
+ });
+ for (const [send, status, code] of [
+ [oversized, 413, "payload_too_large"],
+ [notJson, 415, "unsupported_media_type"],
+ ] as const) {
+ const keyed = await send({ authorization: `Bearer ${key}` });
+ expect(keyed.headers.get("access-control-allow-origin")).toBe("*");
+ expect(await errorOf(keyed)).toMatchObject({ status, code });
+ const keyless = await send({});
+ expect(keyless.headers.get("access-control-allow-origin")).toBeNull();
+ expect(await errorOf(keyless)).toMatchObject({ status, code });
+ }
+ });
+
+ it("an unknown path under the prefix is a JSON 404, not the SPA and not a 401", async () => {
+ for (const path of ["/nope", `/agents/${P}`, "/", `/sessions`]) {
+ const res = await amsp(t, path);
+ expect(res.headers.get("content-type")).toMatch(/^application\/json/);
+ expect(await errorOf(res)).toMatchObject({ status: 404, code: "not_found" });
+ }
+ const keyed = await amsp(t, `/agents/${P}/${A}/whatever`, { key, body: {} });
+ expect(await errorOf(keyed)).toMatchObject({ status: 404, code: "not_found" });
+ });
+});
+
+describe("Agent API: runs", () => {
+ let t: TestApp;
+ let admin: Admin;
+ let key: string;
+ let mock: MockLLM;
+ /** What loading a Session that is not in memory gives (the self-heal case sets it). */
+ let load: SessionLoader["load"] = () => Promise.reject(new Error("nothing to load here"));
+
+ beforeAll(async () => {
+ mock = await startMockLLM((n) => `reply ${n}`);
+ // Titles stay off, so the model is asked for the runs alone.
+ t = await createTestApp({
+ titles: { maybeGenerate: () => {} },
+ loader: { load: (row) => load(row) },
+ });
+ admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);
+ const models = await admin.put(`/api/projects/${P}/models`, {
+ defaultModel: { provider: "custom", modelId: MOCK_MODEL_ID },
+ models: [
+ {
+ provider: "custom",
+ modelId: MOCK_MODEL_ID,
+ apiKey: "sk-mock",
+ baseUrl: mock.url,
+ contextWindow: 200_000,
+ },
+ ],
+ });
+ expect(models.status).toBe(200);
+ key = await expose(admin, A);
+ });
+ afterAll(async () => {
+ await t.deps.manager.shutdown();
+ await t.cleanup();
+ await mock.close();
+ });
+
+ const session = async (sessionId: string): Promise<SessionResponse["session"]> =>
+ ((await (await admin.get(`/api/sessions/${sessionId}`)).json()) as SessionResponse).session;
+
+ it("a run without session_id creates a Session with client api and source api and names it in run.started", async () => {
+ const res = await amsp(t, `/agents/${P}/${A}/runs`, { key, body: { input: "Say hello" } });
+ expect(res.status).toBe(200);
+ expect(res.headers.get("content-type")).toBe("text/event-stream; charset=utf-8");
+ expect(res.headers.get("cache-control")).toBe("no-cache");
+ expect(res.headers.get("x-accel-buffering")).toBe("no");
+ const items = await stream(res).rest();
+ const started = items[0] as Extract<AmspEvent, { type: "run.started" }>;
+ expect(started).toMatchObject({ type: "run.started", agent: `${P}/${A}` });
+ // The real Session's stream: its toolset (first run), one Request answering, the end.
+ const events = items.filter((e): e is AmspEvent => e !== "[DONE]");
+ expect(events.map((e) => e.type)).toEqual([
+ "run.started",
+ "tools.ready",
+ "request.started",
+ "text.delta",
+ "text.delta",
+ "text.done",
+ "request.done",
+ "run.done",
+ ]);
+ expect(events.find((e) => e.type === "text.done")).toMatchObject({
+ text: expect.stringMatching(/^reply \d+$/),
+ });
+ const done = events.at(-1) as Extract<AmspEvent, { type: "run.done" }>;
+ expect(done).toMatchObject({ status: "completed", requests: 1 });
+ expect(done.usage.total).toBeGreaterThan(0);
+ expect(done.usage).toEqual(done.session_usage);
+ expect(items.at(-1)).toBe("[DONE]");
+
+ const created = await session(started.session_id);
+ expect(created).toMatchObject({ client: "api", source: "api", agentId: A });
+ // The caller reads the same Session back through the API.
+ const info = await amsp(t, `/sessions/${started.session_id}`, { key });
+ expect(await info.json()).toMatchObject({
+ session: {
+ id: started.session_id,
+ agent: `${P}/${A}`,
+ status: "idle",
+ model_id: MOCK_MODEL_ID,
+ },
+ });
+ });
+
+ it("the created Session carries the Agent's API approval mode; the tab does not move it, a PATCH on the Session does", async () => {
+ const tab = `/api/projects/${P}/agents/${A}/api`;
+ await admin.put(tab, { approvalMode: "read-only" });
+ try {
+ const first = await stream(
+ await amsp(t, `/agents/${P}/${A}/runs`, { key, body: { input: "one" } }),
+ ).rest();
+ const sessionId = (first[0] as Extract<AmspEvent, { type: "run.started" }>).session_id;
+ expect((await session(sessionId)).approvalMode).toBe("read-only");
+
+ await admin.put(tab, { approvalMode: "deny-all" });
+ expect((await session(sessionId)).approvalMode).toBe("read-only");
+ expect(
+ (await admin.patch(`/api/sessions/${sessionId}`, { approvalMode: "always-ask" })).status,
+ ).toBe(200);
+ expect((await session(sessionId)).approvalMode).toBe("always-ask");
+
+ const second = await stream(
+ await amsp(t, `/agents/${P}/${A}/runs`, { key, body: { input: "two" } }),
+ ).rest();
+ const next = (second[0] as Extract<AmspEvent, { type: "run.started" }>).session_id;
+ expect((await session(next)).approvalMode).toBe("deny-all");
+ } finally {
+ await admin.put(tab, { approvalMode: "allow-all" });
+ }
+ });
+
+ it("a run with session_id continues the same Session and the runtime receives the new input only", async () => {
+ const sessionId = uniqueSessionId();
+ const { session: runtime, runs, release } = blocking(sessionId);
+ adoptSession(t.deps, runtime, { projectId: P, agentId: A, client: "api" });
+ const image = "https://img.test/cat.png";
+ const inputs = [
+ [{ type: "text", text: "first" }],
+ // Items arrive texts first, then images, whatever order they were sent in.
+ [
+ { type: "image_url", image_url: image },
+ { type: "text", text: "second" },
+ ],
+ ];
+ for (const input of inputs) {
+ const events = stream(
+ await amsp(t, `/agents/${P}/${A}/runs`, { key, body: { session_id: sessionId, input } }),
+ );
+ expect(await events.next()).toMatchObject({ type: "run.started", session_id: sessionId });
+ await events.until("text.delta");
+ release();
+ const rest = await events.rest();
+ // The run's own input is the caller's: it is not streamed back.
+ const echoed = rest.filter(
+ (e) =>
+ e !== "[DONE]" &&
+ (e.type === "image_url.done" || (e.type === "text.done" && e.role === "user")),
+ );
+ expect(echoed).toEqual([]);
+ }
+ const received = runs.map((r) =>
+ r.input.map((m) => {
+ const p = m.payload as { text?: string; image_url?: string };
+ return p.text ?? p.image_url;
+ }),
+ );
+ expect(received).toEqual([["first"], ["second", image]]);
+ });
+
+ it("a web-created Session, or another Agent's API Session, is 404 session_not_found", async () => {
+ const web = uniqueSessionId();
+ adoptSession(t.deps, fakeSession(web), { projectId: P, agentId: A, client: "web" });
+ const theirs = uniqueSessionId();
+ adoptSession(t.deps, fakeSession(theirs), {
+ projectId: P,
+ agentId: "agent_creator",
+ client: "api",
+ });
+ for (const sessionId of [web, theirs]) {
+ const run = await amsp(t, `/agents/${P}/${A}/runs`, {
+ key,
+ body: { session_id: sessionId, input: "hi" },
+ });
+ expect(await errorOf(run)).toMatchObject({ status: 404, code: "session_not_found" });
+ }
+ expect(await errorOf(await amsp(t, `/sessions/${web}`, { key }))).toMatchObject({
+ status: 404,
+ code: "session_not_found",
+ });
+ });
+
+ it("a busy Session is 409 and nothing is streamed", async () => {
+ const sessionId = uniqueSessionId();
+ const { session: runtime, runs, release } = blocking(sessionId);
+ adoptSession(t.deps, runtime, { projectId: P, agentId: A, client: "api" });
+ const first = stream(
+ await amsp(t, `/agents/${P}/${A}/runs`, { key, body: { session_id: sessionId, input: "a" } }),
+ );
+ await first.until("text.delta");
+ const second = await amsp(t, `/agents/${P}/${A}/runs`, {
+ key,
+ body: { session_id: sessionId, input: "b" },
+ });
+ expect(second.headers.get("content-type")).toMatch(/^application\/json/);
+ expect(await errorOf(second)).toMatchObject({ status: 409, code: "task_in_progress" });
+ release();
+ await first.rest();
+ expect(runs).toHaveLength(1);
+ });
+
+ it("a Session healed into a new id as it loads is followed: run.started names the new id and the run streams to its end", async () => {
+ const stale = uniqueSessionId();
+ const healed = uniqueSessionId();
+ t.deps.sessionsRepo.insert(sessionRow(stale, { projectId: P, agentId: A, client: "api" }));
+ load = async () =>
+ fakeSession(healed, {
+ async *run() {
+ // A real engine's first record follows its bootstrap I/O.
+ await new Promise((resolve) => setImmediate(resolve));
+ yield requestBegin();
+ yield assistantText("healed");
+ yield requestEnd("completed");
+ },
+ });
+ const items = await stream(
+ await amsp(t, `/agents/${P}/${A}/runs`, { key, body: { session_id: stale, input: "hi" } }),
+ ).rest();
+ expect(items[0]).toMatchObject({ type: "run.started", session_id: healed });
+ expect(items.find((e) => e !== "[DONE]" && e.type === "text.done")).toMatchObject({
+ text: "healed",
+ });
+ expect(items.slice(-2)).toEqual([
+ expect.objectContaining({ type: "run.done", status: "completed" }),
+ "[DONE]",
+ ]);
+ });
+
+ it("the fifth concurrent run of an Agent is 429 with Retry-After, and creates nothing", async () => {
+ await createAgent(admin, "busy_agent");
+ const busyKey = await expose(admin, "busy_agent");
+ const running = Array.from({ length: 4 }, () => blocking(uniqueSessionId()));
+ const streams = [];
+ for (const r of running) {
+ adoptSession(t.deps, r.session, { projectId: P, agentId: "busy_agent", client: "api" });
+ const s = stream(
+ await amsp(t, `/agents/${P}/busy_agent/runs`, {
+ key: busyKey,
+ body: { session_id: r.session.sessionId, input: "go" },
+ }),
+ );
+ await s.until("text.delta");
+ streams.push(s);
+ }
+ const idle = uniqueSessionId();
+ adoptSession(t.deps, fakeSession(idle), { projectId: P, agentId: "busy_agent", client: "api" });
+ const before = t.deps.sessionsRepo.listByAgent(P, "busy_agent").length;
+ for (const body of [{ input: "fifth" }, { session_id: idle, input: "fifth" }]) {
+ const res = await amsp(t, `/agents/${P}/busy_agent/runs`, { key: busyKey, body });
+ expect(res.headers.get("retry-after")).toBe("2");
+ expect(await errorOf(res)).toMatchObject({ status: 429, code: "too_many_runs" });
+ }
+ expect(t.deps.sessionsRepo.listByAgent(P, "busy_agent")).toHaveLength(before);
+ for (const r of running) r.release();
+ for (const s of streams) await s.rest();
+ });
+
+ it.each(AMSP_STREAM_SCRIPTS.map((s) => [s.name, s] as const))(
+ "%s reaches the caller as the fixture records it, ending with exactly one run.done then [DONE]",
+ async (_name, script) => {
+ const decisions: string[] = [];
+ adoptSession(t.deps, scripted(script, decisions), {
+ projectId: P,
+ agentId: A,
+ client: "api",
+ approvalMode: script.approvalMode as ApprovalMode,
+ });
+ const res = await amsp(t, `/agents/${P}/${A}/runs`, {
+ key,
+ body: { session_id: script.sessionId, input: script.input },
+ });
+ const events = stream(res);
+ const read: Array<AmspEvent | "[DONE]"> = [];
+ const asks = script.steps.filter((s) => "approve" in s).length;
+ for (let i = 0; i < asks; i++) {
+ const upTo = await events.until("approval.requested");
+ read.push(...upTo);
+ const ask = upTo.at(-1) as Extract<AmspEvent, { type: "approval.requested" }>;
+ const path = `/sessions/${script.sessionId}/approvals/${ask.tool_call.tool_call_id}`;
+ expect((await amsp(t, path, { key, body: { decision: "allow" } })).status).toBe(204);
+ // Decided: a second answer finds nothing pending.
+ const again = await amsp(t, path, { key, body: { decision: "deny" } });
+ expect(await errorOf(again)).toMatchObject({ status: 404, code: "approval_not_found" });
+ }
+ read.push(...(await events.rest()));
+ expect(pinned(read)).toEqual([...script.events, "[DONE]"]);
+ expect(read.filter((e) => e !== "[DONE]" && e.type === "run.done")).toHaveLength(1);
+ expect(decisions).toEqual(Array.from({ length: asks }, () => "allow"));
+ },
+ );
+
+ it("the Web App's approval route answers the same request, and the caller's answer then finds nothing", async () => {
+ const script = { ...APPROVAL_ROUND_TRIP, sessionId: uniqueSessionId() };
+ const decisions: string[] = [];
+ adoptSession(t.deps, scripted(script, decisions), {
+ projectId: P,
+ agentId: A,
+ client: "api",
+ approvalMode: "always-ask",
+ });
+ const events = stream(
+ await amsp(t, `/agents/${P}/${A}/runs`, {
+ key,
+ body: { session_id: script.sessionId, input: script.input },
+ }),
+ );
+ await events.until("approval.requested");
+ const web = await admin.post(`/api/sessions/${script.sessionId}/approvals/call_1`, {
+ decision: "allow",
+ });
+ expect(web.status).toBe(204);
+ const late = await amsp(t, `/sessions/${script.sessionId}/approvals/call_1`, {
+ key,
+ body: { decision: "deny" },
+ });
+ expect(await errorOf(late)).toMatchObject({ status: 404, code: "approval_not_found" });
+ const rest = await events.rest();
+ expect(rest.at(-2)).toMatchObject({ type: "run.done", status: "completed" });
+ expect(decisions).toEqual(["allow"]);
+ });
+
+ it("a client that disconnects mid-run aborts it", async () => {
+ const sessionId = uniqueSessionId();
+ const { session: runtime, runs } = blocking(sessionId);
+ adoptSession(t.deps, runtime, { projectId: P, agentId: A, client: "api" });
+ const events = stream(
+ await amsp(t, `/agents/${P}/${A}/runs`, {
+ key,
+ body: { session_id: sessionId, input: "go" },
+ }),
+ );
+ await events.until("text.delta");
+ await events.disconnect();
+ await waitFor(() => t.deps.manager.statusOf(sessionId) === "idle");
+ expect(runs[0]!.signal.aborted).toBe(true);
+ });
+
+ it("an explicit abort ends the stream with run.done aborted", async () => {
+ const sessionId = uniqueSessionId();
+ const { session: runtime } = blocking(sessionId);
+ adoptSession(t.deps, runtime, { projectId: P, agentId: A, client: "api" });
+ const events = stream(
+ await amsp(t, `/agents/${P}/${A}/runs`, {
+ key,
+ body: { session_id: sessionId, input: "go" },
+ }),
+ );
+ await events.until("text.delta");
+ expect((await amsp(t, `/sessions/${sessionId}/abort`, { key, method: "POST" })).status).toBe(
+ 202,
+ );
+ const rest = await events.rest();
+ expect(rest.at(-2)).toMatchObject({
+ type: "run.done",
+ status: "aborted",
+ error: { code: "user_abort" },
+ });
+ expect(rest.at(-1)).toBe("[DONE]");
+ expect((await amsp(t, `/sessions/${sessionId}/abort`, { key, method: "POST" })).status).toBe(
+ 204,
+ );
+ });
+
+ it.each([
+ ["a body that is not JSON", "{", "JSON"],
+ ["no input", {}, "input"],
+ ["an empty text item", { input: [{ type: "text", text: " " }] }, "input[0].text"],
+ ["a session_id that is not an id", { input: "hi", session_id: "../x" }, "session_id"],
+ [
+ "a file item",
+ { input: [{ type: "file", fileName: "a.txt", dataBase64: "aGk=" }] },
+ "input[0]",
+ ],
+ [
+ "a data URL that is not an image",
+ { input: [{ type: "image_url", image_url: "data:text/plain;base64,aGk=" }] },
+ "input[0].image_url",
+ ],
+ [
+ "an image over the inline cap",
+ {
+ input: [
+ {
+ type: "image_url",
+ image_url: `data:image/png;base64,${Buffer.alloc(21 * 1024 * 1024).toString("base64")}`,
+ },
+ ],
+ },
+ "input[0].image_url",
+ ],
+ ["an unknown item type", { input: [{ type: "audio" }] }, "input[0].type"],
+ ])("%s is 400 bad_request naming the field, and creates nothing", async (_case, body, field) => {
+ const before = t.deps.sessionsRepo.listByAgent(P, A).length;
+ const res = await amsp(t, `/agents/${P}/${A}/runs`, {
+ key,
+ ...(typeof body === "string" ? { raw: body } : { body }),
+ });
+ const error = (await res.json()) as { error: { code: string; message: string } };
+ expect(res.status).toBe(400);
+ expect(error.error.code).toBe("bad_request");
+ expect(error.error.message).toContain(field);
+ expect(t.deps.sessionsRepo.listByAgent(P, A)).toHaveLength(before);
+ });
+
+ it("images over the per-message total are 400 bad_request", async () => {
+ expect(
+ (await admin.put("/api/admin/settings", { attachmentMaxMb: 1, attachmentTotalMb: 1 })).status,
+ ).toBe(200);
+ try {
+ const image = `data:image/png;base64,${Buffer.alloc(700 * 1024).toString("base64")}`;
+ const res = await amsp(t, `/agents/${P}/${A}/runs`, {
+ key,
+ body: {
+ input: [
+ { type: "image_url", image_url: image },
+ { type: "image_url", image_url: image },
+ ],
+ },
+ });
+ expect(await errorOf(res)).toMatchObject({ status: 400, code: "bad_request" });
+ } finally {
+ await admin.put("/api/admin/settings", { attachmentTotalMb: 120, attachmentMaxMb: 100 });
+ }
+ });
+
+ it("a keep-alive comment is written after 15 s of silence", async () => {
+ const sessionId = uniqueSessionId();
+ const { session: runtime, release } = blocking(sessionId);
+ adoptSession(t.deps, runtime, { projectId: P, agentId: A, client: "api" });
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ try {
+ const res = await amsp(t, `/agents/${P}/${A}/runs`, {
+ key,
+ body: { session_id: sessionId, input: "go" },
+ });
+ const reader = res.body!.getReader();
+ const decoder = new TextDecoder();
+ let text = "";
+ const readUntil = async (needle: string): Promise<void> => {
+ while (!text.includes(needle)) {
+ const { done, value } = await reader.read();
+ if (done) throw new Error(`the body ended before ${JSON.stringify(needle)}`);
+ text += decoder.decode(value, { stream: true });
+ }
+ };
+ await readUntil('"text.delta","at"');
+ await readUntil('"text":"Working"');
+ expect(text).not.toContain(": keep-alive");
+ await vi.advanceTimersByTimeAsync(15_000);
+ await readUntil(": keep-alive\n\n");
+ release();
+ await readUntil("data: [DONE]\n\n");
+ await reader.cancel();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("a server failure while driving ends the stream with run.done fatal internal and [DONE], and stops the run", async () => {
+ const sessionId = uniqueSessionId();
+ const { session: runtime, runs } = blocking(sessionId);
+ adoptSession(t.deps, runtime, { projectId: P, agentId: A, client: "api" });
+ const events = stream(
+ await amsp(t, `/agents/${P}/${A}/runs`, {
+ key,
+ body: { session_id: sessionId, input: "go" },
+ }),
+ );
+ await events.until("text.delta");
+ // A record the translator cannot read stands in for any failure of the server's own.
+ t.deps.channels
+ .get(sessionId)
+ .publish({ timestamp: new Date().toISOString(), type: "model_msg", payload: null });
+ const rest = await events.rest();
+ expect(rest.at(-2)).toMatchObject({
+ type: "run.done",
+ status: "fatal",
+ error: { code: "internal" },
+ });
+ expect(rest.at(-1)).toBe("[DONE]");
+ await waitFor(() => t.deps.manager.statusOf(sessionId) === "idle");
+ expect(runs[0]!.signal.aborted).toBe(true);
+ });
+});
+
+describe("Agent API: the try route", () => {
+ let t: TestApp;
+ let admin: Admin;
+ let member: Admin;
+ let outsider: Admin;
+ let key: string;
+ let mock: MockLLM;
+ const tryPath = (agentId = A) => `/api/projects/${P}/agents/${agentId}/api/try`;
+
+ beforeAll(async () => {
+ mock = await startMockLLM((n) => `reply ${n}`);
+ // Titles stay off, so the model is asked for the runs alone.
+ t = await createTestApp({ titles: { maybeGenerate: () => {} } });
+ admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);
+ const models = await admin.put(`/api/projects/${P}/models`, {
+ defaultModel: { provider: "custom", modelId: MOCK_MODEL_ID },
+ models: [
+ {
+ provider: "custom",
+ modelId: MOCK_MODEL_ID,
+ apiKey: "sk-mock",
+ baseUrl: mock.url,
+ contextWindow: 200_000,
+ },
+ ],
+ });
+ expect(models.status).toBe(200);
+ key = await expose(admin, A, { approvalMode: "read-only" });
+ member = apiClient(t.app, (await provisionUser(t.app, "try_member")).cookie);
+ outsider = apiClient(t.app, (await provisionUser(t.app, "try_outsider")).cookie);
+ expect((await admin.post(`/api/projects/${P}/members`, { userId: "try_member" })).status).toBe(
+ 201,
+ );
+ });
+ afterAll(async () => {
+ await t.deps.manager.shutdown();
+ await t.cleanup();
+ await mock.close();
+ });
+
+ const lastUses = async (): Promise<Array<string | null>> =>
+ (
+ (await (await admin.get(`/api/projects/${P}/agents/${A}/api`)).json()) as AgentApiResponse
+ ).api.keys.map((k) => k.lastUsedAt);
+
+ const types = (items: Array<AmspEvent | "[DONE]">) =>
+ items.map((e) => (e === "[DONE]" ? e : e.type));
+
+ it("the owner's sign-in streams what a keyed run streams; the Session is an API Session with the Agent's approval mode, and no key's last use moves", async () => {
+ const keyed = await stream(
+ await amsp(t, `/agents/${P}/${A}/runs`, { key, body: { input: "What time is it now?" } }),
+ ).rest();
+ const used = await lastUses();
+ expect(used[0]).not.toBeNull();
+
+ const res = await admin.post(tryPath(), { input: "What time is it now?" });
+ expect(res.status).toBe(200);
+ expect(res.headers.get("content-type")).toBe("text/event-stream; charset=utf-8");
+ expect(res.headers.get("x-accel-buffering")).toBe("no");
+ const items = await stream(res).rest();
+ expect(types(items)).toEqual(types(keyed));
+ expect(items.slice(-2)).toEqual([
+ expect.objectContaining({ type: "run.done", status: "completed", requests: 1 }),
+ "[DONE]",
+ ]);
+ const started = items[0] as Extract<AmspEvent, { type: "run.started" }>;
+ expect(started).toMatchObject({ type: "run.started", agent: `${P}/${A}` });
+ const created = (
+ (await (await admin.get(`/api/sessions/${started.session_id}`)).json()) as SessionResponse
+ ).session;
+ expect(created).toMatchObject({
+ client: "api",
+ source: "api",
+ agentId: A,
+ approvalMode: "read-only",
+ });
+ expect(await lastUses()).toEqual(used);
+ });
+
+ it("a member who is not the owner is refused 403 owner_required, a non-member 404, a signed-out request 401, and nothing is created", async () => {
+ const before = t.deps.sessionsRepo.listByAgent(P, A).length;
+ const body = { input: "What time is it now?" };
+ expect(await errorOf(await member.post(tryPath(), body))).toMatchObject({
+ status: 403,
+ code: "owner_required",
+ });
+ expect((await outsider.post(tryPath(), body)).status).toBe(404);
+ const signedOut = await t.app.request(tryPath(), {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ expect(signedOut.status).toBe(401);
+ expect(t.deps.sessionsRepo.listByAgent(P, A)).toHaveLength(before);
+ });
+
+ it("an Agent whose switch is off, or no such Agent, is 404 agent_not_found; the admin's switch off is 403 agent_api_disabled", async () => {
+ await createAgent(admin, "dark_try_agent");
+ const body = { input: "hi" };
+ const dark = await errorOf(await admin.post(tryPath("dark_try_agent"), body));
+ const ghost = await errorOf(await admin.post(tryPath("ghost_try_agent"), body));
+ expect(dark).toMatchObject({ status: 404, code: "agent_not_found" });
+ expect(ghost.body).toBe(dark.body);
+ expect((await admin.put("/api/admin/settings", { agentApiEnabled: false })).status).toBe(200);
+ try {
+ expect(await errorOf(await admin.post(tryPath(), body))).toMatchObject({
+ status: 403,
+ code: "agent_api_disabled",
+ });
+ } finally {
+ await admin.put("/api/admin/settings", { agentApiEnabled: true });
+ }
+ });
+
+ it("a try run with session_id continues an API Session of the Agent; a web Session's id is 404 session_not_found", async () => {
+ const sessionId = uniqueSessionId();
+ const { session: runtime, runs, release } = blocking(sessionId);
+ adoptSession(t.deps, runtime, { projectId: P, agentId: A, client: "api" });
+ const events = stream(
+ await admin.post(tryPath(), { session_id: sessionId, input: "And now?" }),
+ );
+ expect(await events.next()).toMatchObject({ type: "run.started", session_id: sessionId });
+ await events.until("text.delta");
+ release();
+ expect((await events.rest()).at(-1)).toBe("[DONE]");
+ expect(runs.map((r) => r.input.map((m) => (m.payload as { text?: string }).text))).toEqual([
+ ["And now?"],
+ ]);
+
+ const web = uniqueSessionId();
+ adoptSession(t.deps, fakeSession(web), { projectId: P, agentId: A, client: "web" });
+ expect(
+ await errorOf(await admin.post(tryPath(), { session_id: web, input: "hi" })),
+ ).toMatchObject({ status: 404, code: "session_not_found" });
+ });
+
+ it("try runs count toward the Agent's four: the fifth is 429 on the try route and the public route alike", async () => {
+ await createAgent(admin, "busy_try_agent");
+ const busyKey = await expose(admin, "busy_try_agent");
+ const running = Array.from({ length: 4 }, () => blocking(uniqueSessionId()));
+ const streams = [];
+ for (const r of running) {
+ adoptSession(t.deps, r.session, { projectId: P, agentId: "busy_try_agent", client: "api" });
+ const s = stream(
+ await admin.post(tryPath("busy_try_agent"), {
+ session_id: r.session.sessionId,
+ input: "go",
+ }),
+ );
+ await s.until("text.delta");
+ streams.push(s);
+ }
+ const before = t.deps.sessionsRepo.listByAgent(P, "busy_try_agent").length;
+ const viaTry = await admin.post(tryPath("busy_try_agent"), { input: "fifth" });
+ const viaKey = await amsp(t, `/agents/${P}/busy_try_agent/runs`, {
+ key: busyKey,
+ body: { input: "fifth" },
+ });
+ for (const res of [viaTry, viaKey]) {
+ expect(res.headers.get("retry-after")).toBe("2");
+ expect(await errorOf(res)).toMatchObject({ status: 429, code: "too_many_runs" });
+ }
+ expect(t.deps.sessionsRepo.listByAgent(P, "busy_try_agent")).toHaveLength(before);
+ for (const r of running) r.release();
+ for (const s of streams) await s.rest();
+ });
+
+ it.each([
+ ["no input", {}],
+ ["a session_id that is not an id", { input: "hi", session_id: "../x" }],
+ ["a file item", { input: [{ type: "file", fileName: "a.txt", dataBase64: "aGk=" }] }],
+ ])("%s is the public route's 400 bad_request, byte for byte", async (_case, body) => {
+ const viaTry = await errorOf(await admin.post(tryPath(), body));
+ const viaKey = await errorOf(await amsp(t, `/agents/${P}/${A}/runs`, { key, body }));
+ expect(viaTry).toMatchObject({ status: 400, code: "bad_request" });
+ expect(viaTry.body).toBe(viaKey.body);
+ });
+
+ it("a client that disconnects from the try stream aborts the run", async () => {
+ const sessionId = uniqueSessionId();
+ const { session: runtime, runs } = blocking(sessionId);
+ adoptSession(t.deps, runtime, { projectId: P, agentId: A, client: "api" });
+ const events = stream(await admin.post(tryPath(), { session_id: sessionId, input: "go" }));
+ await events.until("text.delta");
+ await events.disconnect();
+ await waitFor(() => t.deps.manager.statusOf(sessionId) === "idle");
+ expect(runs[0]!.signal.aborted).toBe(true);
+ });
+});
diff --git a/packages/server/test/amsp-translate.test.ts b/packages/server/test/amsp-translate.test.ts
new file mode 100644
index 00000000..7d3ceb48
--- /dev/null
+++ b/packages/server/test/amsp-translate.test.ts
@@ -0,0 +1,468 @@
+/**
+ * The AMSP translator: a Session's live stream (what its channel carries) in, the events an
+ * Agent API caller reads out. Pure — every case feeds channel events and reads what comes back.
+ *
+ * Scenarios:
+ * - Given a streamed assistant text, the caller gets one text.delta per start/delta fragment and
+ * one text.done whose text equals the fragments joined.
+ * - Given a partial `stop` fragment, nothing is produced for it.
+ * - Given a complete message no fragment preceded, its .done still arrives (zero deltas).
+ * - Given a request's token_usage, its usage is stamped on that request.done and summed into
+ * run.done, with the Session's cumulative count as session_usage.
+ * - Given a retried request, request.done is retryable with retry_in_ms, the next
+ * request.started carries the next ordinal, and the run still completes.
+ * - Given a request that fails for good (no retry planned), run.done is fatal with that request's
+ * error pair.
+ * - Given a tool call, its fragments carry the id (and the name on the first), its done keeps the
+ * raw arguments string, and its result is attributed by tool_call_id wherever it lands.
+ * - Given two tools running at once, their results interleave and each keeps its tool_call_id.
+ * - Given an approval_request server event, approval.requested carries the call and its origin;
+ * the engine's decision follows as approval.decided.
+ * - Given a compaction, only summary.* sits between compaction.started and compaction.done (the
+ * summary text as summary.done, the compaction's thinking left out), and its usage is the sum
+ * of its attempts.
+ * - Given a child Session's stream, its session_meta opens it as context.opened with its origin,
+ * and its messages carry that origin and count their own requests without moving the main
+ * Session's ordinals. (A main Session's next context is written to the Trace, not streamed.)
+ * - Given the run's own input on the channel, it is not echoed; a steering text and a harness
+ * injection are, as user text.done with their sender; anything published before the input is
+ * not this run's.
+ * - Given an abort event, run.done is aborted with the abort's error code.
+ * - Given the max-turns notice (an assistant text ending fatal, no error recorded), run.done is
+ * fatal without an error; a compaction that failed at a Task boundary does not end the run if
+ * a request follows.
+ * - Given task_state re-published as running, the run goes on; idle ends it with exactly one
+ * run.done, after which nothing more is produced.
+ */
+import { describe, expect, it } from "vitest";
+import {
+ abortEvent,
+ approvalDecision,
+ assistantText,
+ compactionBegin,
+ compactionEnd,
+ partialText,
+ partialThinking,
+ partialToolCall,
+ partialToolCallOutput,
+ requestBegin,
+ requestEnd,
+ sessionMeta,
+ thinkingMessage,
+ tokenUsage,
+ toolCall,
+ toolCallOutput,
+ userText,
+ withOrigin,
+} from "@lmliheng/penguin-core";
+import type { OmniMessage, TokenCounts } from "@lmliheng/penguin-core";
+import type { AmspEvent } from "@lmliheng/amsp";
+import type { ServerEvent } from "../src/api/types.js";
+import { AmspTranslator } from "../src/amsp/translate.js";
+
+const NOW = new Date("2026-10-07T10:00:00.000Z");
+const counts = (output: number, total: number): TokenCounts => ({
+ cache_read: 0,
+ cache_write: 0,
+ output,
+ total,
+});
+
+/** A translator for a run whose input is `input`, with that input already echoed (the run has started). */
+function startRun(input: OmniMessage[] = [userText("go")]) {
+ const translator = new AmspTranslator(input, { now: () => NOW });
+ let seq = 0;
+ const message = (m: OmniMessage): AmspEvent[] =>
+ translator.feed({ id: `e-${++seq}`, data: JSON.stringify(m) });
+ const server = (e: ServerEvent): AmspEvent[] =>
+ translator.feed({ id: `e-${++seq}`, event: "server_event", data: JSON.stringify(e) });
+ for (const m of input) message(m);
+ return {
+ translator,
+ message,
+ server,
+ /** Feeds every message, then the idle flip; returns everything produced. */
+ play: (messages: OmniMessage[]): AmspEvent[] => [
+ ...messages.flatMap(message),
+ ...server({ type: "task_state", state: "idle" }),
+ ],
+ };
+}
+
+const types = (events: AmspEvent[]): string[] => events.map((e) => e.type);
+const runDone = (events: AmspEvent[]) => {
+ const done = events.filter((e) => e.type === "run.done");
+ expect(done).toHaveLength(1);
+ return done[0] as Extract<AmspEvent, { type: "run.done" }>;
+};
+
+describe("AMSP translator", () => {
+ it("a streamed assistant text reaches the caller as text.delta fragments and one text.done whose text equals the fragments joined", () => {
+ const events = startRun().play([
+ requestBegin(),
+ partialText("start"),
+ partialText("delta", "Hel"),
+ partialText("delta", "lo"),
+ partialText("stop"),
+ assistantText("Hello"),
+ requestEnd("completed"),
+ ]);
+ const deltas = events.filter((e) => e.type === "text.delta");
+ expect(deltas.map((e) => (e as { text: string }).text)).toEqual(["", "Hel", "lo"]);
+ const done = events.find((e) => e.type === "text.done") as { text: string };
+ expect(done.text).toBe(deltas.map((e) => (e as { text: string }).text).join(""));
+ expect(types(events)).toEqual([
+ "request.started",
+ "text.delta",
+ "text.delta",
+ "text.delta",
+ "text.done",
+ "request.done",
+ "run.done",
+ ]);
+ });
+
+ it("a partial stop fragment produces no event", () => {
+ const { message } = startRun();
+ expect(message(partialText("stop"))).toEqual([]);
+ expect(message(partialThinking("stop"))).toEqual([]);
+ expect(message(partialToolCall({ eventType: "stop", name: "", toolCallId: "c" }))).toEqual([]);
+ expect(message(partialToolCallOutput({ eventType: "stop", toolCallId: "c" }))).toEqual([]);
+ });
+
+ it("a complete message without a preceding start still produces its .done (zero deltas)", () => {
+ const events = startRun().play([
+ requestBegin(),
+ thinkingMessage("let me think"),
+ assistantText("Plain."),
+ requestEnd("completed"),
+ ]);
+ expect(types(events)).toEqual([
+ "request.started",
+ "thinking.done",
+ "text.done",
+ "request.done",
+ "run.done",
+ ]);
+ });
+
+ it("the usage of a request is stamped on its request.done and summed into run.done", () => {
+ const events = startRun().play([
+ requestBegin(),
+ assistantText("one"),
+ tokenUsage(counts(2, 100), counts(2, 100)),
+ requestEnd("completed"),
+ requestBegin(),
+ assistantText("two"),
+ tokenUsage(counts(5, 250), counts(3, 150)),
+ requestEnd("completed"),
+ ]);
+ const requests = events.filter((e) => e.type === "request.done") as Array<{
+ usage: TokenCounts | null;
+ }>;
+ expect(requests.map((r) => r.usage)).toEqual([counts(2, 100), counts(3, 150)]);
+ const done = runDone(events);
+ expect(done.status).toBe("completed");
+ expect(done.requests).toBe(2);
+ expect(done.usage).toEqual(counts(5, 250));
+ expect(done.session_usage).toEqual(counts(5, 250));
+ });
+
+ it("a retried request yields request.done retryable with retry_in_ms, then a new request.started with the next ordinal", () => {
+ const events = startRun().play([
+ requestBegin(),
+ requestEnd("retryable", {
+ errorCode: "network",
+ errorMessage: "fetch failed",
+ attempt: 1,
+ retryInMs: 1000,
+ }),
+ requestBegin(),
+ assistantText("ok"),
+ requestEnd("completed", { attempt: 2 }),
+ ]);
+ expect(events[1]).toMatchObject({
+ type: "request.done",
+ request: 1,
+ status: "retryable",
+ usage: null,
+ error: { code: "network", message: "fetch failed" },
+ attempt: 1,
+ retry_in_ms: 1000,
+ });
+ expect(events[2]).toMatchObject({ type: "request.started", request: 2 });
+ const done = runDone(events);
+ expect(done.status).toBe("completed");
+ expect(done.error).toBeUndefined();
+ expect(done.requests).toBe(2);
+ });
+
+ it("a terminal request failure makes run.done fatal with the request's error pair", () => {
+ const events = startRun().play([
+ requestBegin(),
+ requestEnd("fatal", { errorCode: "auth", errorMessage: "401 invalid key", attempt: 1 }),
+ ]);
+ const done = runDone(events);
+ expect(done.status).toBe("fatal");
+ expect(done.error).toEqual({ code: "auth", message: "401 invalid key" });
+ });
+
+ it("a tool call's fragments carry the id and name, and the tool result is attributed by tool_call_id", () => {
+ const args = '{"command": "ls"}';
+ const events = startRun().play([
+ requestBegin(),
+ partialToolCall({ eventType: "start", name: "exec_command", toolCallId: "call_1" }),
+ partialToolCall({ eventType: "delta", name: "", arguments: args, toolCallId: "call_1" }),
+ partialToolCall({ eventType: "stop", name: "", toolCallId: "call_1" }),
+ // The complete call's arguments are the engine's own serialization: forwarded as they are,
+ // never rebuilt from (or checked against) the fragments.
+ toolCall({ name: "exec_command", arguments: '{"command":"ls"}', toolCallId: "call_1" }),
+ approvalDecision("allow", "call_1"),
+ partialToolCallOutput({ eventType: "start", toolCallId: "call_1" }),
+ requestEnd("completed"),
+ partialToolCallOutput({ eventType: "delta", output: "a\n", toolCallId: "call_1" }),
+ toolCallOutput({ output: "a\n", toolCallId: "call_1" }),
+ ]);
+ expect(events.filter((e) => e.type === "tool_call.delta")).toMatchObject([
+ { tool_call_id: "call_1", name: "exec_command", arguments: "" },
+ { tool_call_id: "call_1", name: "", arguments: args },
+ ]);
+ expect(events.find((e) => e.type === "tool_call.done")).toMatchObject({
+ tool_call_id: "call_1",
+ name: "exec_command",
+ arguments: '{"command":"ls"}',
+ stop_reason: "completed",
+ });
+ expect(
+ events
+ .filter((e) => e.type.startsWith("tool_result."))
+ .map((e) => [e.type, (e as { tool_call_id: string }).tool_call_id]),
+ ).toEqual([
+ ["tool_result.delta", "call_1"],
+ ["tool_result.delta", "call_1"],
+ ["tool_result.done", "call_1"],
+ ]);
+ });
+
+ it("parallel tool results interleave and are attributed by tool_call_id", () => {
+ const image = "data:image/png;base64,iVBORw0KGgo=";
+ const events = startRun().play([
+ partialToolCallOutput({ eventType: "delta", output: "a1", toolCallId: "a" }),
+ partialToolCallOutput({ eventType: "delta", output: "b1", toolCallId: "b" }),
+ partialToolCallOutput({ eventType: "delta", toolCallId: "b", images: [image] }),
+ toolCallOutput({ output: "b1", toolCallId: "b", images: [image] }),
+ partialToolCallOutput({ eventType: "delta", output: "a2", toolCallId: "a" }),
+ toolCallOutput({ output: "a1a2", toolCallId: "a" }),
+ ]);
+ const results = events.filter((e) => e.type.startsWith("tool_result.")) as Array<{
+ type: string;
+ tool_call_id: string;
+ output: string;
+ images?: string[];
+ }>;
+ expect(results.map((r) => `${r.type}:${r.tool_call_id}:${r.output}`)).toEqual([
+ "tool_result.delta:a:a1",
+ "tool_result.delta:b:b1",
+ "tool_result.delta:b:",
+ "tool_result.done:b:b1",
+ "tool_result.delta:a:a2",
+ "tool_result.done:a:a1a2",
+ ]);
+ expect(results[2]!.images).toEqual([image]);
+ expect(results[3]!.images).toEqual([image]);
+ });
+
+ it("an approval_request server event becomes approval.requested and the decision follows", () => {
+ const { server, message } = startRun();
+ const call = toolCall({ name: "write_file", arguments: '{"path":"x"}', toolCallId: "call_9" });
+ expect(server({ type: "approval_request", toolCall: call, origin: ["child-1"] })).toEqual([
+ {
+ type: "approval.requested",
+ at: NOW.toISOString(),
+ origin: ["child-1"],
+ tool_call: { tool_call_id: "call_9", name: "write_file", arguments: '{"path":"x"}' },
+ },
+ ]);
+ expect(message(approvalDecision("deny", "call_9"))).toMatchObject([
+ { type: "approval.decided", tool_call_id: "call_9", decision: "deny" },
+ ]);
+ });
+
+ it("compaction encloses summary items, never text or thinking items, and its usage sums its attempts", () => {
+ const events = startRun().play([
+ compactionBegin({ reason: "context", mode: "summarize", context: 9000, turns: 4 }),
+ partialThinking("start"),
+ partialThinking("delta", "condensing"),
+ thinkingMessage("condensing"),
+ partialText("start"),
+ partialText("delta", "Sum"),
+ tokenUsage(counts(9, 900), counts(3, 300)),
+ tokenUsage(counts(12, 1200), counts(3, 300)),
+ compactionEnd({ reason: "context", mode: "summarize", status: "completed", attempt: 2 }),
+ requestBegin(),
+ assistantText("after"),
+ requestEnd("completed"),
+ ]);
+ const start = events.findIndex((e) => e.type === "compaction.started");
+ const end = events.findIndex((e) => e.type === "compaction.done");
+ expect(types(events.slice(start + 1, end))).toEqual(["summary.delta", "summary.delta"]);
+ expect(events[end]).toMatchObject({ status: "completed", usage: counts(6, 600), attempt: 2 });
+ // The next context's Request follows; the text after the compaction is the answer again.
+ expect(types(events.slice(end + 1))).toEqual([
+ "request.started",
+ "text.done",
+ "request.done",
+ "run.done",
+ ]);
+ // A summary that arrives complete (nothing streamed) is its summary.done.
+ const whole = startRun().play([
+ compactionBegin({ reason: "manual", mode: "summarize", context: 10, turns: 1 }),
+ assistantText("The whole summary."),
+ compactionEnd({ reason: "manual", mode: "summarize", status: "completed" }),
+ ]);
+ expect(types(whole)).toEqual([
+ "compaction.started",
+ "summary.done",
+ "compaction.done",
+ "run.done",
+ ]);
+ expect(runDone(events).usage).toEqual(counts(6, 600));
+ });
+
+ it("a child Session's session_meta opens it as context.opened, and its messages carry its origin without disturbing the main Session's request numbering", () => {
+ const child = "session-child-1";
+ const childMeta = sessionMeta({
+ session_id: child,
+ provider: "custom",
+ model_id: "m2",
+ model_context_window: "unknown",
+ system_prompt: "",
+ agent_state: "/a",
+ workspace: "/w",
+ source: "subagent",
+ });
+ const events = startRun().play([
+ requestBegin(),
+ withOrigin(childMeta, child),
+ withOrigin(requestBegin(), child),
+ withOrigin(assistantText("child text"), child),
+ withOrigin(tokenUsage(counts(1, 50), counts(1, 50)), child),
+ withOrigin(requestEnd("completed"), child),
+ withOrigin(requestBegin(), child),
+ withOrigin(requestEnd("completed"), child),
+ tokenUsage(counts(4, 400), counts(4, 400)),
+ requestEnd("completed"),
+ requestBegin(),
+ requestEnd("completed"),
+ ]);
+ const requests = events.filter((e) => e.type === "request.started") as Array<{
+ request: number;
+ origin?: string[];
+ }>;
+ expect(requests.map((r) => [r.origin?.[0] ?? "main", r.request])).toEqual([
+ ["main", 1],
+ [child, 1],
+ [child, 2],
+ ["main", 2],
+ ]);
+ // The child's stream opens with its context, ahead of its first Request.
+ expect(events[1]).toMatchObject({
+ type: "context.opened",
+ origin: [child],
+ session_id: child,
+ provider: "custom",
+ model_id: "m2",
+ context_window: "unknown",
+ });
+ expect(events[2]).toMatchObject({ type: "request.started", origin: [child] });
+ expect(events.find((e) => e.type === "text.done")).toMatchObject({ origin: [child] });
+ const done = runDone(events);
+ // The child's usage is part of the run's spend; the Session's own count is the main one.
+ expect(done.usage).toEqual(counts(5, 450));
+ expect(done.session_usage).toEqual(counts(4, 400));
+ expect(done.requests).toBe(4);
+ });
+
+ it("the run's own input is not echoed, a steering user text is (with its sender), and nothing published before the input counts", () => {
+ const input = [userText("the question")];
+ const translator = new AmspTranslator(input, { now: () => NOW });
+ const feed = (m: OmniMessage | ServerEvent, server = false) =>
+ translator.feed({
+ id: "x",
+ ...(server ? { event: "server_event" } : {}),
+ data: JSON.stringify(m),
+ });
+ // Before the run's input: an idle flip a child's state change re-published, a stray output.
+ expect(feed({ type: "task_state", state: "idle" }, true)).toEqual([]);
+ expect(feed(assistantText("not this run's"))).toEqual([]);
+ expect(feed(input[0]!)).toEqual([]);
+ expect(feed(userText("[user_steering]\nfaster\n[/user_steering]"))).toMatchObject([
+ { type: "text.done", role: "user", text: "[user_steering]\nfaster\n[/user_steering]" },
+ ]);
+ expect(feed(userText("[background_task_done]", "harness"))).toMatchObject([
+ { type: "text.done", role: "user", sender: "harness" },
+ ]);
+ expect(feed({ type: "task_state", state: "idle" }, true)).toMatchObject([
+ { type: "run.done", status: "completed" },
+ ]);
+ });
+
+ it("an abort event ends the run aborted with the abort's error code", () => {
+ const events = startRun().play([
+ requestBegin(),
+ partialText("start"),
+ partialText("delta", "Let me"),
+ assistantText("Let me", "aborted"),
+ requestEnd("aborted", { attempt: 1 }),
+ abortEvent("user_abort"),
+ ]);
+ const done = runDone(events);
+ expect(done.status).toBe("aborted");
+ expect(done.error?.code).toBe("user_abort");
+ // A child's abort is the child's business.
+ const child = startRun().play([withOrigin(abortEvent("user_abort"), "child")]);
+ expect(runDone(child).status).toBe("completed");
+ });
+
+ it("the max-turns notice ends the run fatal without an error pair", () => {
+ const events = startRun().play([
+ requestBegin(),
+ requestEnd("completed"),
+ partialText("start"),
+ partialText("delta", "[reached max turns (1); stopping]"),
+ partialText("stop", "", "fatal"),
+ assistantText("[reached max turns (1); stopping]", "fatal"),
+ ]);
+ const done = runDone(events);
+ expect(done.status).toBe("fatal");
+ expect(done.error).toBeUndefined();
+ });
+
+ it("a compaction that failed is the run's end only when no request follows it", () => {
+ const failed = compactionEnd({
+ reason: "context",
+ mode: "summarize",
+ status: "fatal",
+ errorCode: "rejected",
+ errorMessage: "400 context too long",
+ });
+ const begin = compactionBegin({ reason: "context", mode: "summarize", context: 1, turns: 1 });
+ const ended = startRun().play([begin, failed]);
+ expect(runDone(ended)).toMatchObject({
+ status: "fatal",
+ error: { code: "rejected", message: "400 context too long" },
+ });
+ const continued = startRun().play([begin, failed, requestBegin(), requestEnd("completed")]);
+ expect(runDone(continued).status).toBe("completed");
+ });
+
+ it("a task_state re-published while running does not end the run; idle does, once", () => {
+ const { server, message } = startRun();
+ expect(server({ type: "task_state", state: "running", queued: 1 })).toEqual([]);
+ expect(message(requestBegin())).toHaveLength(1);
+ const end = server({ type: "task_state", state: "idle" });
+ expect(types(end)).toEqual(["run.done"]);
+ expect(server({ type: "task_state", state: "idle" })).toEqual([]);
+ expect(message(assistantText("late"))).toEqual([]);
+ });
+});
diff --git a/packages/server/test/db-migrations.test.ts b/packages/server/test/db-migrations.test.ts
index 9eca5f69..0e70a842 100644
--- a/packages/server/test/db-migrations.test.ts
+++ b/packages/server/test/db-migrations.test.ts
@@ -45,6 +45,13 @@ const GOAL_STATE_DDL = `
CREATE INDEX idx_goal_session ON goal_state(session_id);
`;
+/** Migration 15's two tables and index: a database stamped before it had none of them. */
+function dropAgentApi(db: DatabaseSync): void {
+ db.exec("DROP INDEX IF EXISTS idx_agent_api_keys_agent");
+ db.exec("DROP TABLE IF EXISTS agent_api_keys");
+ db.exec("DROP TABLE IF EXISTS agent_api");
+}
+
/** Every company-mode table the migrations add: a database from before them had none. */
function dropCompanyModeTables(db: DatabaseSync): void {
for (const table of [
@@ -71,6 +78,7 @@ function open024(): DatabaseSync {
const db = new sqlite.DatabaseSync(":memory:");
db.exec(SCHEMA_SQL);
db.exec("DROP TABLE IF EXISTS model_provider_auth_tokens");
+ dropAgentApi(db);
db.exec("DROP TABLE IF EXISTS model_promotions");
dropCompanyModeTables(db);
db.exec("DROP TABLE messaging_bindings");
@@ -114,6 +122,7 @@ function open6(): DatabaseSync {
const db = new sqlite.DatabaseSync(":memory:");
db.exec(SCHEMA_SQL);
db.exec("DROP TABLE IF EXISTS model_provider_auth_tokens");
+ dropAgentApi(db);
db.exec("DROP TABLE IF EXISTS model_promotions");
db.exec(PRE_CHANNEL_CHAT_DDL);
// SCHEMA_SQL declares the CURRENT shape; migration 8's queue, migration 13's came after 6, and
@@ -132,6 +141,7 @@ function open7(): DatabaseSync {
db.exec("DROP TABLE IF EXISTS org_desk_notices");
db.exec("DROP TABLE IF EXISTS org_desk_mentions");
db.exec("DROP TABLE IF EXISTS model_provider_auth_tokens");
+ dropAgentApi(db);
db.exec("DROP TABLE IF EXISTS model_promotions");
dropUsageCostColumns(db);
db.exec("PRAGMA user_version = 7");
@@ -143,6 +153,7 @@ function open8(): DatabaseSync {
const db = new sqlite.DatabaseSync(":memory:");
db.exec(SCHEMA_SQL);
db.exec("DROP TABLE IF EXISTS model_provider_auth_tokens");
+ dropAgentApi(db);
db.exec("DROP TABLE IF EXISTS model_promotions");
db.exec("DROP TABLE IF EXISTS org_desk_mentions");
dropUsageCostColumns(db);
@@ -155,17 +166,22 @@ function open9(): DatabaseSync {
const db = new sqlite.DatabaseSync(":memory:");
db.exec(SCHEMA_SQL);
db.exec("DROP TABLE IF EXISTS model_provider_auth_tokens");
+ dropAgentApi(db);
db.exec("DROP TABLE IF EXISTS org_desk_mentions");
dropUsageCostColumns(db);
db.exec("PRAGMA user_version = 9");
return db;
}
-/** A database stamped at migration 12: everything the current declaration has but the desk-mention queue. */
+/**
+ * A database stamped at migration 12: everything the current declaration has but the desk-mention
+ * queue, the fixed cost and the Agent API.
+ */
function open12(): DatabaseSync {
const db = new sqlite.DatabaseSync(":memory:");
db.exec(SCHEMA_SQL);
db.exec("DROP TABLE IF EXISTS org_desk_mentions");
+ dropAgentApi(db);
dropUsageCostColumns(db);
db.exec("PRAGMA user_version = 12");
return db;
@@ -176,6 +192,7 @@ function open029(): DatabaseSync {
const db = new sqlite.DatabaseSync(":memory:");
db.exec(SCHEMA_SQL);
db.exec("DROP TABLE IF EXISTS model_provider_auth_tokens");
+ dropAgentApi(db);
db.exec("DROP TABLE IF EXISTS model_promotions");
dropCompanyModeTables(db);
db.exec(GOAL_STATE_DDL);
@@ -198,6 +215,7 @@ function openPreProfile(): DatabaseSync {
const db = new sqlite.DatabaseSync(":memory:");
db.exec(SCHEMA_SQL);
db.exec("DROP TABLE IF EXISTS model_provider_auth_tokens");
+ dropAgentApi(db);
db.exec("DROP TABLE IF EXISTS model_promotions");
dropProfileColumns(db);
// Version 4 predates company mode as well: its three migrations (6–8) come after the
@@ -210,12 +228,14 @@ function openPreProfile(): DatabaseSync {
/**
* A database from before costs were fixed at record time: today's declaration minus exactly the
- * two usage_records columns migration 14 adds, stamped at the version before it.
+ * two usage_records columns migration 14 adds and the Agent API tables migration 15 adds,
+ * stamped at the version before both.
*/
function openPreUsageCost(): DatabaseSync {
const db = new sqlite.DatabaseSync(":memory:");
db.exec(SCHEMA_SQL);
dropUsageCostColumns(db);
+ dropAgentApi(db);
db.exec("PRAGMA user_version = 13");
return db;
}
@@ -624,8 +644,9 @@ describe("migration 8 → current: model-promotions", () => {
"machines-columns",
"company-mode-desk-mentions",
"usage-record-cost",
+ "agent-api",
]);
- expect(schemaVersion(db)).toBe(14);
+ expect(schemaVersion(db)).toBe(15);
expect(promotionsTableExists()).toEqual({ "1": 1 });
expect(authTokensTableExists()).toEqual({ "1": 1 });
@@ -648,8 +669,9 @@ describe("migration 8 → current: model-promotions", () => {
"machines-columns",
"company-mode-desk-mentions",
"usage-record-cost",
+ "agent-api",
]);
- expect(schemaVersion(db)).toBe(14);
+ expect(schemaVersion(db)).toBe(15);
} finally {
db.close();
}
@@ -672,8 +694,9 @@ describe("migration 9 → current: model-provider-auth-tokens", () => {
"machines-columns",
"company-mode-desk-mentions",
"usage-record-cost",
+ "agent-api",
]);
- expect(schemaVersion(db)).toBe(14);
+ expect(schemaVersion(db)).toBe(15);
expect(tableExists()).toEqual({ "1": 1 });
db.exec(
"INSERT INTO users (user_id, password_hash, is_admin, created_at)" +
@@ -716,7 +739,11 @@ describe("migration 12 → current: company-mode-desk-mentions", () => {
try {
fresh.exec(SCHEMA_SQL);
expect(shape(db)).not.toBe(shape(fresh));
- expect(migrate(db).applied).toEqual(["company-mode-desk-mentions", "usage-record-cost"]);
+ expect(migrate(db).applied).toEqual([
+ "company-mode-desk-mentions",
+ "usage-record-cost",
+ "agent-api",
+ ]);
expect(schemaVersion(db)).toBe(LATEST_VERSION);
expect(shape(db)).toBe(shape(fresh));
queue(db, "msg-1");
@@ -816,6 +843,89 @@ describe("pre-cost → current: usage-record-cost", () => {
});
});
+/** A database stamped at migration 13: everything before the fixed cost and the Agent API. */
+function open13(): DatabaseSync {
+ const db = new sqlite.DatabaseSync(":memory:");
+ db.exec(SCHEMA_SQL);
+ dropUsageCostColumns(db);
+ dropAgentApi(db);
+ db.exec("PRAGMA user_version = 13");
+ return db;
+}
+
+describe("migration 13 → current: agent-api", () => {
+ it("creates the settings table while a pushed platform boots: one row per Agent, keyed and allow-all unless set", () => {
+ const db = open13();
+ try {
+ expect(migrate(db, { swapPath: true }).applied).toEqual(["usage-record-cost", "agent-api"]);
+ expect(schemaVersion(db)).toBe(15);
+ const enable = () =>
+ db
+ .prepare(
+ "INSERT INTO agent_api (project_id, agent_id, enabled, updated_at)" +
+ " VALUES ('p1', 'coder', 1, '2026-10-07T00:00:00.000Z')",
+ )
+ .run();
+ enable();
+ expect(db.prepare("SELECT enabled, open, approval_mode FROM agent_api").all()).toEqual([
+ { enabled: 1, open: 0, approval_mode: "allow-all" },
+ ]);
+ // The (project, agent) pair is the key: a second row for the same Agent is refused.
+ expect(enable).toThrow(/UNIQUE/);
+ } finally {
+ db.close();
+ }
+ });
+
+ it("creates the keys table, which holds one key per token hash and only keys a user created", () => {
+ const db = open13();
+ try {
+ migrate(db);
+ db.exec("PRAGMA foreign_keys = ON");
+ db.exec(
+ "INSERT INTO users (user_id, password_hash, is_admin, created_at)" +
+ " VALUES ('alice', 'hash', 0, '2026-10-07T00:00:00.000Z')",
+ );
+ const insert = (keyId: string, hash: string, createdBy: string) =>
+ db
+ .prepare(
+ "INSERT INTO agent_api_keys (key_id, project_id, agent_id, token_hash, prefix, name, created_by, created_at)" +
+ " VALUES (?, 'p1', 'coder', ?, 'penguin_abcdefgh', 'ci', ?, '2026-10-07T00:00:00.000Z')",
+ )
+ .run(keyId, hash, createdBy);
+ insert("k1", "h1", "alice");
+ // A token hash names one key, so the lookup by hash is never ambiguous.
+ expect(() => insert("k2", "h1", "alice")).toThrow(/UNIQUE/);
+ expect(() => insert("k3", "h3", "ghost")).toThrow(/FOREIGN KEY/);
+ expect(db.prepare("SELECT key_id, last_used_at FROM agent_api_keys").all()).toEqual([
+ { key_id: "k1", last_used_at: null },
+ ]);
+ } finally {
+ db.close();
+ }
+ });
+
+ it("down drops the settings and every key, and a second up recreates both empty", () => {
+ const db = open13();
+ const at13 = open13();
+ try {
+ migrate(db);
+ db.exec(
+ "INSERT INTO agent_api (project_id, agent_id, enabled, updated_at)" +
+ " VALUES ('p1', 'coder', 1, '2026-10-07T00:00:00.000Z')",
+ );
+ rollbackTo(db, 13);
+ expect(schemaVersion(db)).toBe(13);
+ expect(shape(db)).toBe(shape(at13));
+ migrate(db);
+ expect(db.prepare("SELECT COUNT(*) AS n FROM agent_api").get()).toEqual({ n: 0 });
+ } finally {
+ db.close();
+ at13.close();
+ }
+ });
+});
+
describe("0.2.4 → current", () => {
/** The whole point: an older runtime's database becomes what a current build creates. */
it("brings a 0.2.4 database to the shape a fresh one is created with", () => {
diff --git a/packages/server/test/fixtures/amsp-stream.ts b/packages/server/test/fixtures/amsp-stream.ts
new file mode 100644
index 00000000..68c9e0ad
--- /dev/null
+++ b/packages/server/test/fixtures/amsp-stream.ts
@@ -0,0 +1,515 @@
+/**
+ * Scripted AMSP runs, shared by the server's wire suite (amsp-routes.test.ts) and the client's
+ * (packages/amsp/test, which imports this file read-only).
+ *
+ * Each script is one run: the internal stream a Session's runtime yields for it (OmniMessage
+ * envelopes, as plain JSON — `{ approve }` steps mark where the runtime asks for an approval) and
+ * the AMSP events the caller receives for it, `run.started` through `run.done`. The server suite
+ * plays `steps` through a fake Session and checks the stream it reads back equals `events`; the
+ * client suite serves `toSse(events)` as the response body.
+ *
+ * Every `at` the server stamps itself (`run.started`, `run.done`, `approval.requested`) reads
+ * AMSP_FIXTURE_NOW here; the wire suite compares those after pinning them to it. Everything else
+ * carries the timestamp of the message it was projected from.
+ *
+ * Self-contained on purpose — only type imports — so the client package can read it without
+ * depending on the server or core.
+ */
+import type { AmspEvent } from "@lmliheng/amsp";
+
+/** The `at` of every server-stamped event in `events`. */
+export const AMSP_FIXTURE_NOW = "2026-10-07T10:00:00.000Z";
+
+/** The Agent the scripts run on, as the wire names it (`<projectId>/<agentId>`). */
+export const AMSP_FIXTURE_AGENT = "default_project/default_agent";
+
+/** One step of a script's internal stream: a message the runtime yields, or an approval it asks for. */
+export type AmspScriptStep =
+ | { message: Record<string, unknown> }
+ | { approve: { tool_call_id: string; name: string; arguments: string } };
+
+export interface AmspStreamScript {
+ /** What the scenario is, for test names. */
+ name: string;
+ /** The API Session the run continues. */
+ sessionId: string;
+ /** The approval mode the Session runs with (an asking one when a step asks). */
+ approvalMode: "allow-all" | "always-ask";
+ /** The request body's `input`. */
+ input: string;
+ /** What the Session's runtime does for the run, in order. */
+ steps: AmspScriptStep[];
+ /** What the caller receives, in order, before `data: [DONE]`. */
+ events: AmspEvent[];
+}
+
+/** The response body a server writes for `events`: one `data:` block each, then `[DONE]`. */
+export function toSse(events: readonly AmspEvent[]): string {
+ return [...events.map((e) => `data: ${JSON.stringify(e)}\n\n`), "data: [DONE]\n\n"].join("");
+}
+
+const at = (ms: number): string => `2026-10-07T10:00:00.${String(ms).padStart(3, "0")}Z`;
+const msg = (
+ ms: number,
+ type: "model_msg" | "event_msg" | "session_meta",
+ payload: Record<string, unknown>,
+ origin?: string[],
+): AmspScriptStep => ({
+ message: { timestamp: at(ms), type, payload, ...(origin !== undefined ? { origin } : {}) },
+});
+const usage = (output: number, total: number) => ({
+ cache_read: 0,
+ cache_write: 0,
+ output,
+ total,
+});
+
+/** A plain answer: one Request, streamed text, its usage. */
+export const PLAIN_ANSWER: AmspStreamScript = {
+ name: "a plain answer",
+ sessionId: "session-2026-10-07-10-00-00-a0000001",
+ approvalMode: "allow-all",
+ input: "Say hello",
+ steps: [
+ msg(100, "event_msg", { type: "request_begin" }),
+ msg(110, "model_msg", {
+ type: "partial_text",
+ role: "assistant",
+ event_type: "start",
+ text: "",
+ stop_reason: "completed",
+ }),
+ msg(120, "model_msg", {
+ type: "partial_text",
+ role: "assistant",
+ event_type: "delta",
+ text: "Hello",
+ stop_reason: "completed",
+ }),
+ msg(130, "model_msg", {
+ type: "partial_text",
+ role: "assistant",
+ event_type: "delta",
+ text: "!",
+ stop_reason: "completed",
+ }),
+ msg(140, "model_msg", {
+ type: "partial_text",
+ role: "assistant",
+ event_type: "stop",
+ text: "",
+ stop_reason: "completed",
+ }),
+ msg(150, "model_msg", {
+ type: "text",
+ role: "assistant",
+ text: "Hello!",
+ stop_reason: "completed",
+ }),
+ msg(160, "event_msg", { type: "token_usage", session: usage(2, 412), request: usage(2, 412) }),
+ msg(170, "event_msg", { type: "request_end", status: "completed" }),
+ ],
+ events: [
+ {
+ type: "run.started",
+ at: AMSP_FIXTURE_NOW,
+ session_id: "session-2026-10-07-10-00-00-a0000001",
+ agent: AMSP_FIXTURE_AGENT,
+ },
+ { type: "request.started", at: at(100), request: 1 },
+ { type: "text.delta", at: at(110), role: "assistant", text: "" },
+ { type: "text.delta", at: at(120), role: "assistant", text: "Hello" },
+ { type: "text.delta", at: at(130), role: "assistant", text: "!" },
+ { type: "text.done", at: at(150), role: "assistant", text: "Hello!", stop_reason: "completed" },
+ {
+ type: "request.done",
+ at: at(170),
+ request: 1,
+ status: "completed",
+ usage: usage(2, 412),
+ },
+ {
+ type: "run.done",
+ at: AMSP_FIXTURE_NOW,
+ status: "completed",
+ requests: 1,
+ usage: usage(2, 412),
+ session_usage: usage(2, 412),
+ },
+ ],
+};
+
+const LS_ARGS = '{"command":"ls"}';
+
+/**
+ * A tool call the caller approves, then a second Request. The tool runs while its Request is
+ * still open: the approval and the start of the result arrive before `request.done`, the rest
+ * after it — as the engine streams them.
+ */
+export const APPROVAL_ROUND_TRIP: AmspStreamScript = {
+ name: "a tool call the caller approves",
+ sessionId: "session-2026-10-07-10-00-00-a0000002",
+ approvalMode: "always-ask",
+ input: "List the files",
+ steps: [
+ msg(100, "event_msg", { type: "request_begin" }),
+ msg(110, "model_msg", {
+ type: "partial_tool_call",
+ role: "assistant",
+ event_type: "start",
+ name: "exec_command",
+ arguments: "",
+ tool_call_id: "call_1",
+ stop_reason: "completed",
+ }),
+ msg(120, "model_msg", {
+ type: "partial_tool_call",
+ role: "assistant",
+ event_type: "delta",
+ name: "",
+ arguments: LS_ARGS,
+ tool_call_id: "call_1",
+ stop_reason: "completed",
+ }),
+ msg(130, "model_msg", {
+ type: "partial_tool_call",
+ role: "assistant",
+ event_type: "stop",
+ name: "",
+ arguments: "",
+ tool_call_id: "call_1",
+ stop_reason: "completed",
+ }),
+ msg(140, "model_msg", {
+ type: "tool_call",
+ role: "assistant",
+ name: "exec_command",
+ arguments: LS_ARGS,
+ tool_call_id: "call_1",
+ stop_reason: "completed",
+ }),
+ { approve: { tool_call_id: "call_1", name: "exec_command", arguments: LS_ARGS } },
+ msg(150, "event_msg", { type: "approval_decision", decision: "allow", tool_call_id: "call_1" }),
+ msg(160, "model_msg", {
+ type: "partial_tool_call_output",
+ role: "user",
+ event_type: "start",
+ output: "",
+ tool_call_id: "call_1",
+ stop_reason: "completed",
+ }),
+ msg(170, "event_msg", {
+ type: "token_usage",
+ session: usage(12, 500),
+ request: usage(12, 500),
+ }),
+ msg(180, "event_msg", { type: "request_end", status: "completed" }),
+ msg(190, "model_msg", {
+ type: "partial_tool_call_output",
+ role: "user",
+ event_type: "delta",
+ output: "README.md\nsrc\n",
+ tool_call_id: "call_1",
+ stop_reason: "completed",
+ }),
+ msg(200, "model_msg", {
+ type: "partial_tool_call_output",
+ role: "user",
+ event_type: "stop",
+ output: "",
+ tool_call_id: "call_1",
+ stop_reason: "completed",
+ }),
+ msg(210, "model_msg", {
+ type: "tool_call_output",
+ role: "user",
+ output: "README.md\nsrc\n",
+ tool_call_id: "call_1",
+ stop_reason: "completed",
+ }),
+ msg(220, "event_msg", { type: "request_begin" }),
+ msg(230, "model_msg", {
+ type: "text",
+ role: "assistant",
+ text: "Two entries: README.md and src.",
+ stop_reason: "completed",
+ }),
+ msg(240, "event_msg", {
+ type: "token_usage",
+ session: usage(22, 1100),
+ request: usage(10, 600),
+ }),
+ msg(250, "event_msg", { type: "request_end", status: "completed" }),
+ ],
+ events: [
+ {
+ type: "run.started",
+ at: AMSP_FIXTURE_NOW,
+ session_id: "session-2026-10-07-10-00-00-a0000002",
+ agent: AMSP_FIXTURE_AGENT,
+ },
+ { type: "request.started", at: at(100), request: 1 },
+ {
+ type: "tool_call.delta",
+ at: at(110),
+ tool_call_id: "call_1",
+ name: "exec_command",
+ arguments: "",
+ },
+ { type: "tool_call.delta", at: at(120), tool_call_id: "call_1", name: "", arguments: LS_ARGS },
+ {
+ type: "tool_call.done",
+ at: at(140),
+ tool_call_id: "call_1",
+ name: "exec_command",
+ arguments: LS_ARGS,
+ stop_reason: "completed",
+ },
+ {
+ type: "approval.requested",
+ at: AMSP_FIXTURE_NOW,
+ tool_call: { tool_call_id: "call_1", name: "exec_command", arguments: LS_ARGS },
+ },
+ { type: "approval.decided", at: at(150), tool_call_id: "call_1", decision: "allow" },
+ { type: "tool_result.delta", at: at(160), tool_call_id: "call_1", output: "" },
+ {
+ type: "request.done",
+ at: at(180),
+ request: 1,
+ status: "completed",
+ usage: usage(12, 500),
+ },
+ {
+ type: "tool_result.delta",
+ at: at(190),
+ tool_call_id: "call_1",
+ output: "README.md\nsrc\n",
+ },
+ {
+ type: "tool_result.done",
+ at: at(210),
+ tool_call_id: "call_1",
+ output: "README.md\nsrc\n",
+ stop_reason: "completed",
+ },
+ { type: "request.started", at: at(220), request: 2 },
+ {
+ type: "text.done",
+ at: at(230),
+ role: "assistant",
+ text: "Two entries: README.md and src.",
+ stop_reason: "completed",
+ },
+ {
+ type: "request.done",
+ at: at(250),
+ request: 2,
+ status: "completed",
+ usage: usage(10, 600),
+ },
+ {
+ type: "run.done",
+ at: AMSP_FIXTURE_NOW,
+ status: "completed",
+ requests: 2,
+ usage: usage(22, 1100),
+ session_usage: usage(22, 1100),
+ },
+ ],
+};
+
+const CHILD = "session-2026-10-07-10-00-01-c0000001";
+
+/**
+ * A run with everything a caller collecting "the answer" must leave out: a steering message,
+ * a subagent child's own context and reply (origin-tagged), and a compaction whose summary
+ * streams as `summary.delta` (the engine streams a summary's fragments or its complete text,
+ * never both). The answer is the main Session's two assistant texts.
+ */
+export const MIXED_RUN: AmspStreamScript = {
+ name: "a run with steering, a subagent and a compaction",
+ sessionId: "session-2026-10-07-10-00-00-a0000003",
+ approvalMode: "allow-all",
+ input: "Fix the build",
+ steps: [
+ msg(100, "event_msg", { type: "request_begin" }),
+ msg(110, "model_msg", {
+ type: "text",
+ role: "assistant",
+ text: "Working on it.",
+ stop_reason: "completed",
+ }),
+ msg(120, "event_msg", { type: "token_usage", session: usage(4, 300), request: usage(4, 300) }),
+ msg(130, "event_msg", { type: "request_end", status: "completed" }),
+ msg(140, "model_msg", {
+ type: "text",
+ role: "user",
+ text: "[user_steering]\nalso run the tests\n[/user_steering]",
+ stop_reason: "completed",
+ }),
+ msg(
+ 150,
+ "session_meta",
+ {
+ session_id: CHILD,
+ provider: "custom",
+ model_id: "m1",
+ model_context_window: 128000,
+ system_prompt: "",
+ agent_state: "/data/default_project/agents/default_agent/agent_state",
+ workspace: "/tmp/w",
+ source: "subagent",
+ },
+ [CHILD],
+ ),
+ msg(160, "event_msg", { type: "request_begin" }, [CHILD]),
+ msg(
+ 170,
+ "model_msg",
+ { type: "text", role: "assistant", text: "Tests pass.", stop_reason: "completed" },
+ [CHILD],
+ ),
+ msg(180, "event_msg", { type: "token_usage", session: usage(3, 200), request: usage(3, 200) }, [
+ CHILD,
+ ]),
+ msg(190, "event_msg", { type: "request_end", status: "completed" }, [CHILD]),
+ msg(200, "event_msg", {
+ type: "compaction_begin",
+ reason: "context",
+ mode: "summarize",
+ context: 300,
+ turns: 1,
+ }),
+ msg(210, "model_msg", {
+ type: "partial_text",
+ role: "assistant",
+ event_type: "start",
+ text: "",
+ stop_reason: "completed",
+ }),
+ msg(220, "model_msg", {
+ type: "partial_text",
+ role: "assistant",
+ event_type: "delta",
+ text: "Summary.",
+ stop_reason: "completed",
+ }),
+ msg(230, "model_msg", {
+ type: "partial_text",
+ role: "assistant",
+ event_type: "stop",
+ text: "",
+ stop_reason: "completed",
+ }),
+ msg(240, "event_msg", { type: "token_usage", session: usage(9, 700), request: usage(5, 400) }),
+ msg(250, "event_msg", {
+ type: "compaction_end",
+ reason: "context",
+ mode: "summarize",
+ status: "completed",
+ attempt: 1,
+ }),
+ msg(260, "event_msg", { type: "request_begin" }),
+ msg(270, "model_msg", {
+ type: "text",
+ role: "assistant",
+ text: "Done: the build is green.",
+ stop_reason: "completed",
+ }),
+ msg(280, "event_msg", { type: "token_usage", session: usage(15, 900), request: usage(6, 200) }),
+ msg(290, "event_msg", { type: "request_end", status: "completed" }),
+ ],
+ events: [
+ {
+ type: "run.started",
+ at: AMSP_FIXTURE_NOW,
+ session_id: "session-2026-10-07-10-00-00-a0000003",
+ agent: AMSP_FIXTURE_AGENT,
+ },
+ { type: "request.started", at: at(100), request: 1 },
+ {
+ type: "text.done",
+ at: at(110),
+ role: "assistant",
+ text: "Working on it.",
+ stop_reason: "completed",
+ },
+ { type: "request.done", at: at(130), request: 1, status: "completed", usage: usage(4, 300) },
+ {
+ type: "text.done",
+ at: at(140),
+ role: "user",
+ text: "[user_steering]\nalso run the tests\n[/user_steering]",
+ stop_reason: "completed",
+ },
+ {
+ type: "context.opened",
+ at: at(150),
+ origin: [CHILD],
+ session_id: CHILD,
+ provider: "custom",
+ model_id: "m1",
+ context_window: 128000,
+ },
+ { type: "request.started", at: at(160), origin: [CHILD], request: 1 },
+ {
+ type: "text.done",
+ at: at(170),
+ origin: [CHILD],
+ role: "assistant",
+ text: "Tests pass.",
+ stop_reason: "completed",
+ },
+ {
+ type: "request.done",
+ at: at(190),
+ origin: [CHILD],
+ request: 1,
+ status: "completed",
+ usage: usage(3, 200),
+ },
+ {
+ type: "compaction.started",
+ at: at(200),
+ reason: "context",
+ mode: "summarize",
+ context: 300,
+ turns: 1,
+ },
+ { type: "summary.delta", at: at(210), text: "" },
+ { type: "summary.delta", at: at(220), text: "Summary." },
+ {
+ type: "compaction.done",
+ at: at(250),
+ reason: "context",
+ mode: "summarize",
+ status: "completed",
+ usage: usage(5, 400),
+ attempt: 1,
+ },
+ { type: "request.started", at: at(260), request: 2 },
+ {
+ type: "text.done",
+ at: at(270),
+ role: "assistant",
+ text: "Done: the build is green.",
+ stop_reason: "completed",
+ },
+ { type: "request.done", at: at(290), request: 2, status: "completed", usage: usage(6, 200) },
+ {
+ type: "run.done",
+ at: AMSP_FIXTURE_NOW,
+ status: "completed",
+ requests: 3,
+ usage: usage(18, 1100),
+ session_usage: usage(15, 900),
+ },
+ ],
+};
+
+/** Every script, for suites that play them all. */
+export const AMSP_STREAM_SCRIPTS: readonly AmspStreamScript[] = [
+ PLAIN_ANSWER,
+ APPROVAL_ROUND_TRIP,
+ MIXED_RUN,
+];
diff --git a/packages/server/test/helpers.ts b/packages/server/test/helpers.ts
index 9f937cfb..3aec40b8 100644
--- a/packages/server/test/helpers.ts
+++ b/packages/server/test/helpers.ts
@@ -513,17 +513,29 @@ export async function provisionUser(
/** JSON request client that carries the cookie. */
export function apiClient(app: Hono<AppEnv>, cookie: string) {
+ return clientWith(app, { cookie });
+}
+
+/**
+ * JSON request client as a Session's tool subprocess calls the server: the boot's local API
+ * token (`t.deps.authService.localApiToken()`) as a Bearer header, and no cookie.
+ */
+export function tokenClient(app: Hono<AppEnv>, token: string) {
+ return clientWith(app, { authorization: `Bearer ${token}` });
+}
+
+function clientWith(app: Hono<AppEnv>, credential: Record<string, string>) {
const call = (method: string) => (apiPath: string, body?: unknown) =>
app.request(apiPath, {
method,
headers: {
- cookie,
+ ...credential,
...(body !== undefined ? { "content-type": "application/json" } : {}),
},
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
});
return {
- get: (apiPath: string) => app.request(apiPath, { headers: { cookie } }),
+ get: (apiPath: string) => app.request(apiPath, { headers: credential }),
post: call("POST"),
put: call("PUT"),
patch: call("PATCH"),
diff --git a/packages/server/test/hot-replace.test.ts b/packages/server/test/hot-replace.test.ts
index 1263e8e6..d88eb8c6 100644
--- a/packages/server/test/hot-replace.test.ts
+++ b/packages/server/test/hot-replace.test.ts
@@ -45,6 +45,8 @@ function memorySettings(maxMb = 7): Settings {
set: (k, v) => void kv.set(k, v),
getCompanyMode: () => false,
setCompanyMode: () => {},
+ getAgentApiEnabled: () => true,
+ setAgentApiEnabled: () => {},
getProxyForApp: () => false,
setProxyForApp: () => {},
getProxyForAgent: () => false,
diff --git a/packages/server/test/session-loader.test.ts b/packages/server/test/session-loader.test.ts
index 7710c8b4..933d4113 100644
--- a/packages/server/test/session-loader.test.ts
+++ b/packages/server/test/session-loader.test.ts
@@ -4,7 +4,8 @@
* missing session_meta) all collapse into HttpError(409, session_unrecoverable),
* preserving the original core message instead of bubbling up as a 500. A Session rebuilt
* without a Trace records the source this process knows, else the one its row stands for
- * (`company` on the organization runtime's `org` row), else core's default.
+ * (`company` on the organization runtime's `org` row, `api` on the Agent API's `api` row), else
+ * core's default.
*/
import fs from "node:fs/promises";
import path from "node:path";
@@ -103,7 +104,7 @@ describe("session-loader", () => {
expect((err as HttpError).code).toBe("workspace_missing");
});
- it("self-heal rebuild re-records a registry-known source in the fresh session_meta; an unknown one is company on an org row, user on any other", async () => {
+ it("self-heal rebuild re-records a registry-known source in the fresh session_meta; an unknown one is company on an org row, api on an api row, user on any other", async () => {
// The anthropic pair constructs without a credential (the same pair session-index
// creates over HTTP); custom/m1 would demand a key at client construction.
await saveProjectConfig(root, PROJECT, {
@@ -137,15 +138,21 @@ describe("session-loader", () => {
expect(unknownMeta.payload.source).toBe("user");
(unknown as unknown as { dispose(): void }).dispose();
- // The same on a row the organization runtime opened (a desk waiting for its first run):
- // the row says what the Session is, a company Session.
- const desk = await createCoreSessionLoader(root, new SessionSources()).load({
- ...healRow,
- client: "org",
- });
- const deskMeta = (desk as unknown as { metaMessage: { payload: { source?: string } } })
- .metaMessage;
- expect(deskMeta.payload.source).toBe("company");
- (desk as unknown as { dispose(): void }).dispose();
+ // The same on a row only the server writes, waiting for its first run: the row says what
+ // the Session is — a company Session on the organization runtime's, an API Session on the
+ // Agent API's.
+ for (const [client, source] of [
+ ["org", "company"],
+ ["api", "api"],
+ ] as const) {
+ const rebuilt = await createCoreSessionLoader(root, new SessionSources()).load({
+ ...healRow,
+ client,
+ });
+ const rebuiltMeta = (rebuilt as unknown as { metaMessage: { payload: { source?: string } } })
+ .metaMessage;
+ expect(rebuiltMeta.payload.source, client).toBe(source);
+ (rebuilt as unknown as { dispose(): void }).dispose();
+ }
});
});
diff --git a/packages/server/test/session-source.test.ts b/packages/server/test/session-source.test.ts
index 64b71ca5..191c5df4 100644
--- a/packages/server/test/session-source.test.ts
+++ b/packages/server/test/session-source.test.ts
@@ -27,7 +27,7 @@
* way.
* - Given a Session company mode opened before the source was required (a head without one, the
* row's client `org`), it reads as `company` and is in no category; so does an `org` row that
- * has not run yet.
+ * has not run yet. An `api` row that has not run yet reads as `api`, in Background.
* - Given company mode opening a desk Session (`company`, client `org`), the Session is
* `company`, keeps its `org` client and is in no category; a child it spawns is `subagent`,
* in Background.
@@ -289,27 +289,35 @@ describe("session source", () => {
expect(counted.counts).toEqual({ active: 0, background: 0, archived: 0 });
});
- it("reads an org row that has not run yet as company, in no category", async () => {
- // A desk opened at a hire and never run, after a restart: no Trace, nothing in the
- // registry. (Its first run records `company` too: session-loader.test.ts.)
- const sessionId = `session-2026-07-21-09-${String(cases).padStart(2, "0")}-00-0de5c001`;
- const stamp = "2026-07-21T09:00:00.000Z";
- t.deps.sessionsRepo.insert({
- sessionId,
- projectId,
- agentId,
- provider: "anthropic",
- modelId: "claude-sonnet-4-6",
- workspace: t.root,
- approvalMode: "allow-all",
- title: null,
- client: "org",
- createdAt: stamp,
- lastActiveAt: stamp,
- });
- expect(sourceIn(await list(""), sessionId)).toBe("company");
- expect((await list("?counts=1")).counts).toEqual({ active: 0, background: 0, archived: 0 });
- });
+ it.each([
+ // A desk opened at a hire and never run.
+ ["an org row", "org", "company", { active: 0, background: 0, archived: 0 }],
+ // An API Session whose first run never got as far as its Trace.
+ ["an api row", "api", "api", { active: 0, background: 1, archived: 0 }],
+ ] as const)(
+ "reads %s that has not run yet as the source its client stands for",
+ async (_row, client, source, counts) => {
+ // After a restart: no Trace, nothing in the registry. (Its first run records that source
+ // too: session-loader.test.ts.)
+ const sessionId = `session-2026-07-21-09-${String(cases).padStart(2, "0")}-00-0de5c001`;
+ const stamp = "2026-07-21T09:00:00.000Z";
+ t.deps.sessionsRepo.insert({
+ sessionId,
+ projectId,
+ agentId,
+ provider: "anthropic",
+ modelId: "claude-sonnet-4-6",
+ workspace: t.root,
+ approvalMode: "allow-all",
+ title: null,
+ client,
+ createdAt: stamp,
+ lastActiveAt: stamp,
+ });
+ expect(sourceIn(await list(""), sessionId)).toBe(source);
+ expect((await list("?counts=1")).counts).toEqual(counts);
+ },
+ );
it("opens a company-mode desk Session as company, keeping its org client, in no category", async () => {
await configureModels();
diff --git a/packages/ui-gallery/src/app/mock/client.ts b/packages/ui-gallery/src/app/mock/client.ts
index a58602ce..a0e88112 100644
--- a/packages/ui-gallery/src/app/mock/client.ts
+++ b/packages/ui-gallery/src/app/mock/client.ts
@@ -8,6 +8,7 @@
* runs in the wrong order.
*/
import { ApiError } from "./errors";
+import { answerAsResponse } from "./fetch-shim";
import { router } from "./routes";
import { getStore } from "./store";
import type { Method } from "./router";
@@ -74,3 +75,26 @@ export async function apiFetchWithMeta<T>(
if (answer.kind === "raw") return { data: answer.body as T, serverNowMs };
return { data: answer.body as T, serverNowMs };
}
+
+export interface ApiFetchStreamOptions {
+ method?: "GET" | "POST";
+ body?: unknown;
+ signal?: AbortSignal;
+}
+
+/**
+ * The app's `apiFetchStream`: the router's answer as a Response, its body unread for the caller
+ * to stream, and a refusal as the same ApiError the app's client throws.
+ */
+export async function apiFetchStream(
+ path: string,
+ options: ApiFetchStreamOptions = {},
+): Promise<Response> {
+ await beat();
+ if (options.signal?.aborted) throw options.signal.reason;
+ const response = await answerAsResponse(options.method ?? "GET", path, options.body);
+ if (response.ok) return response;
+ const { error } = (await response.json()) as { error: { code: string; message: string } };
+ if (response.status === 401 && !isAuthEndpoint(path)) onUnauthorized?.();
+ throw new ApiError(response.status, error.code, error.message);
+}
diff --git a/packages/ui-gallery/src/app/mock/fixtures.ts b/packages/ui-gallery/src/app/mock/fixtures.ts
index c157f922..b1c91a24 100644
--- a/packages/ui-gallery/src/app/mock/fixtures.ts
+++ b/packages/ui-gallery/src/app/mock/fixtures.ts
@@ -7,6 +7,7 @@
* data in step with the app that reads it.
*/
import type {
+ AgentApiSettings,
AgentConfigResponse,
AgentSummary,
BenchmarkCaseSummary,
@@ -54,6 +55,8 @@ import {
presetModelEntries,
presetPromotions,
} from "../../../../core/dist/state/model-catalog.js";
+// The AMSP wire types, by path: the gallery reads them as types only and takes no dependency.
+import type { AmspEvent } from "../../../../amsp/src/types";
import { IDS } from "./ids";
import type { Lang } from "./types";
import type { ModelRef } from "./transcripts";
@@ -152,6 +155,8 @@ export interface DemoFixtures {
vault: Record<string, VaultResponse>;
/** The signed-in account's own vault — the user-level table `/api/me/vault` serves. */
userVault: VaultResponse;
+ /** Each Agent's public API settings, keyed by Agent id; an Agent missing here never had them set. */
+ agentApi: Record<string, AgentApiSettings>;
workspace: { entries: Record<string, WorkspaceFileEntry[]>; content: Record<string, string> };
chatDefaults: ChatDefaultsDto;
commandPolicy: CommandPolicyDto;
@@ -238,6 +243,8 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {
hookCount: 1,
pluginUpdates: [{ name: IDS.plugins.registry, version: "2026.09.20.1" }],
memoryCount: 4,
+ // Its API is on: see `agentApi` below.
+ apiEnabled: true,
},
{
agentId: IDS.agents.notes,
@@ -260,6 +267,7 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {
hookCount: 0,
pluginUpdates: [],
memoryCount: 0,
+ apiEnabled: false,
},
];
@@ -1182,6 +1190,33 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {
],
};
+ // The docs Agent answers programs: one key in daily use, one minted and never used.
+ const agentApi: DemoFixtures["agentApi"] = {
+ [IDS.agents.docs]: {
+ enabled: true,
+ open: false,
+ approvalMode: "allow-all",
+ keys: [
+ {
+ keyId: "kq3VtX9cRb2LmN0a",
+ name: L("文档站检索", "docs-site search"),
+ prefix: "penguin_Zr8kQ2vT",
+ createdBy: user.userId,
+ createdAt: iso(ago(21)),
+ lastUsedAt: iso(ago(0, 12)),
+ },
+ {
+ keyId: "Hc7pW2sYd4EfJ6uB",
+ name: L("每周报告脚本", "weekly report script"),
+ prefix: "penguin_4mGxL7pA",
+ createdBy: user.userId,
+ createdAt: iso(ago(2)),
+ lastUsedAt: null,
+ },
+ ],
+ },
+ };
+
const file = (name: string, sizeBytes: number, days: number): WorkspaceFileEntry => ({
name,
kind: "file",
@@ -1503,6 +1538,7 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {
attachmentMaxMb: 100,
attachmentTotalMb: 120,
companyMode: false,
+ agentApiEnabled: true,
},
// A ledger with one of everything the page has a branch for: a class that is never a
// candidate, three that are, a duplicate-looking environment pair, and one path the scan
@@ -1768,6 +1804,7 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {
memory,
vault,
userVault,
+ agentApi,
workspace,
chatDefaults,
commandPolicy,
@@ -1779,3 +1816,161 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {
usageErrors,
};
}
+
+// ---------------------------------------------------------------------------------------------
+// The API tab's Try it: one run's AMSP stream
+// ---------------------------------------------------------------------------------------------
+
+/** The Session the demo's Try it runs open. */
+export const TRY_SESSION_ID = "session-2026-10-09-09-30-00-7d2e41c8";
+
+/** `date`'s own format, in UTC: `Fri Oct 9 09:30:00 UTC 2026`. */
+function dateOutput(ms: number): string {
+ const d = new Date(ms);
+ const day = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][d.getUTCDay()];
+ const month = d.toLocaleString("en", { month: "short", timeZone: "UTC" });
+ const date = String(d.getUTCDate()).padStart(2, " ");
+ const time = d.toISOString().slice(11, 19);
+ return `${day} ${month} ${date} ${time} UTC ${d.getUTCFullYear()}`;
+}
+
+/**
+ * The body the try route streams, as `data:` lines and `[DONE]`: the example question answered
+ * by running `date` over two Requests — the tool call's fragments and the complete call, its
+ * result, then the answer's fragments and the complete answer, so the rendered view has
+ * fragments to merge; a run that continues a Session gets one answer in one Request.
+ */
+export function amspTryStream(
+ body: unknown,
+ run: { agent: string; lang: Lang; now: number },
+): string {
+ const { agent, lang, now } = run;
+ const L = <T>(zh: T, en: T): T => (lang === "zh" ? zh : en);
+ const sessionField = (body as { session_id?: unknown } | null)?.session_id;
+ const sessionId = typeof sessionField === "string" ? sessionField : TRY_SESSION_ID;
+ let clock = now;
+ const at = (stepMs: number) => new Date((clock += stepMs)).toISOString();
+ const usage = (output: number, total: number, cacheRead: number) => ({
+ cache_read: cacheRead,
+ cache_write: 0,
+ output,
+ total,
+ });
+ const started: AmspEvent = {
+ type: "run.started",
+ at: at(0),
+ session_id: sessionId,
+ agent,
+ };
+ let events: AmspEvent[];
+ if (typeof sessionField === "string") {
+ const answer = usage(38, 3120, 2944);
+ events = [
+ started,
+ { type: "request.started", at: at(120), request: 1 },
+ {
+ type: "text.done",
+ at: at(1400),
+ role: "assistant",
+ text: L(
+ "演示数据只回答第一个问题;真实的 Agent 会在这里接着同一个会话作答。",
+ "The demo answers only the first question; a real agent would carry on this conversation here.",
+ ),
+ stop_reason: "completed",
+ },
+ { type: "request.done", at: at(20), request: 1, status: "completed", usage: answer },
+ {
+ type: "run.done",
+ at: at(10),
+ status: "completed",
+ requests: 1,
+ usage: answer,
+ session_usage: usage(124, 5848, 5184),
+ },
+ ];
+ } else {
+ const call = usage(31, 1376, 1152);
+ const answer = usage(55, 1352, 1088);
+ const clockText = dateOutput(now + 1900);
+ const answerText = L(
+ `现在是 ${clockText.slice(11, 16)}(UTC),${new Date(now).getUTCFullYear()} 年 ${new Date(now).getUTCMonth() + 1} 月 ${new Date(now).getUTCDate()} 日。`,
+ `It is ${clockText.slice(11, 16)} UTC on ${clockText.slice(0, 10)}, ${new Date(now).getUTCFullYear()}.`,
+ );
+ // The answer as a model streams it: three fragments, then the complete text.
+ const third = Math.ceil(answerText.length / 3);
+ const fragments = [0, 1, 2].map((i) => answerText.slice(i * third, (i + 1) * third));
+ events = [
+ started,
+ {
+ type: "context.opened",
+ at: at(60),
+ session_id: sessionId,
+ provider: "anthropic",
+ model_id: "claude-sonnet-5",
+ context_window: 200000,
+ },
+ {
+ type: "tools.ready",
+ at: at(20),
+ tools: ["exec_command", "read_file", "write_file", "edit_file", "web_fetch"].map(
+ (name) => ({ name, description: "" }),
+ ),
+ },
+ { type: "request.started", at: at(40), request: 1 },
+ {
+ type: "tool_call.delta",
+ at: at(1200),
+ tool_call_id: "toolu_try_date",
+ name: "exec_command",
+ arguments: '{"cmd": ',
+ },
+ {
+ type: "tool_call.delta",
+ at: at(200),
+ tool_call_id: "toolu_try_date",
+ name: "",
+ arguments: '"date"}',
+ },
+ {
+ type: "tool_call.done",
+ at: at(100),
+ tool_call_id: "toolu_try_date",
+ name: "exec_command",
+ arguments: '{"cmd":"date"}',
+ stop_reason: "completed",
+ },
+ {
+ type: "tool_result.done",
+ at: at(260),
+ tool_call_id: "toolu_try_date",
+ output: `${clockText}\n`,
+ stop_reason: "completed",
+ },
+ { type: "request.done", at: at(10), request: 1, status: "completed", usage: call },
+ { type: "request.started", at: at(30), request: 2 },
+ ...fragments.map((text): AmspEvent => ({
+ type: "text.delta",
+ at: at(400),
+ role: "assistant",
+ text,
+ })),
+ {
+ type: "text.done",
+ at: at(10),
+ role: "assistant",
+ text: answerText,
+ stop_reason: "completed",
+ },
+ { type: "request.done", at: at(20), request: 2, status: "completed", usage: answer },
+ {
+ type: "run.done",
+ at: at(10),
+ status: "completed",
+ requests: 2,
+ usage: usage(86, 2728, 2240),
+ session_usage: usage(86, 2728, 2240),
+ },
+ ];
+ }
+ return [...events.map((e) => JSON.stringify(e)), "[DONE]"].map((d) => `data: ${d}\n\n`).join("");
+}
diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.ts
index e186173a..a942f7b7 100644
--- a/packages/ui-gallery/src/app/mock/routes.ts
+++ b/packages/ui-gallery/src/app/mock/routes.ts
@@ -11,6 +11,10 @@
import type {
AdminUserCreateResponse,
AdminUsersResponse,
+ AgentApiKeyCreateResponse,
+ AgentApiKeyInfo,
+ AgentApiResponse,
+ AgentApiSettings,
AgentConfigResponse,
AgentCreateResponse,
AgentHooksResponse,
@@ -22,6 +26,7 @@ import type {
AgentsResponse,
AgentVaultConfigDto,
AllProjectSchedulesResponse,
+ ApprovalMode,
AuthResponse,
BenchmarkCasesResponse,
BuiltinBrowserHistoryResponse,
@@ -134,7 +139,7 @@ import type {
// The catalog decides which groups publish a balance, as it does on the server.
import { providerInfo } from "../../../../core/dist/state/model-catalog.js";
import { READ_ONLY } from "./errors";
-import { dayKey, planId, trashId } from "./fixtures";
+import { amspTryStream, dayKey, planId, trashId } from "./fixtures";
import type { DemoFixtures, UsageDay } from "./fixtures";
import { IDS } from "./ids";
import { empty, fail, json, raw, Router } from "./router";
@@ -949,6 +954,7 @@ router
hookCount: 0,
pluginUpdates: [],
memoryCount: 0,
+ apiEnabled: false,
};
store.f.agents.push(agent);
const template = store.f.agentConfigs[IDS.agents.notes]!;
@@ -1033,6 +1039,101 @@ router
return empty();
});
+// ---------------------------------------------------------------------------------------------
+// An Agent's public API: its switches, approval mode and keys (the stream itself is not mocked)
+// ---------------------------------------------------------------------------------------------
+
+const API_APPROVAL_MODES: readonly ApprovalMode[] = [
+ "allow-all",
+ "deny-all",
+ "read-only",
+ "always-ask",
+];
+
+/** `n` random bytes as base64url, the alphabet the server's keys and key ids are written in. */
+function base64url(n: number): string {
+ const bytes = crypto.getRandomValues(new Uint8Array(n));
+ return btoa(String.fromCharCode(...bytes))
+ .replace(/\+/g, "-")
+ .replace(/\//g, "_")
+ .replace(/=+$/, "");
+}
+
+/**
+ * The Agent's settings, as the server reads an Agent never configured: off, keyed, allow-all.
+ * The store's own object: answers hand out a copy, as a server's JSON would, since the app keeps
+ * what it is given and a later write here must not reach into its state.
+ */
+const apiOf = (ctx: Ctx): AgentApiSettings => {
+ const agentId = agentOf(ctx).agentId;
+ ctx.store.f.agentApi[agentId] ??= {
+ enabled: false,
+ open: false,
+ approvalMode: "allow-all",
+ keys: [],
+ };
+ return ctx.store.f.agentApi[agentId];
+};
+
+router
+ .get("/api/projects/:projectId/agents/:agentId/api", (ctx): AgentApiResponse => ({
+ api: structuredClone(apiOf(ctx)),
+ serverEnabled: ctx.store.f.serverSettings.agentApiEnabled,
+ }))
+ .put("/api/projects/:projectId/agents/:agentId/api", (ctx): AgentApiResponse => {
+ const settings = apiOf(ctx);
+ const { enabled, open, approvalMode } = record(ctx.body);
+ if (typeof enabled === "boolean") {
+ settings.enabled = enabled;
+ agentOf(ctx).apiEnabled = enabled;
+ }
+ if (typeof open === "boolean") settings.open = open;
+ const mode = API_APPROVAL_MODES.find((m) => m === approvalMode);
+ if (mode !== undefined) settings.approvalMode = mode;
+ return {
+ api: structuredClone(settings),
+ serverEnabled: ctx.store.f.serverSettings.agentApiEnabled,
+ };
+ })
+ .post("/api/projects/:projectId/agents/:agentId/api/keys", (ctx): unknown => {
+ const settings = apiOf(ctx);
+ const name = str(record(ctx.body).name).trim();
+ if (name.length < 1 || name.length > 64) {
+ fail(400, "bad_request", "A key's name is 1 to 64 characters.");
+ }
+ const secret = `penguin_${base64url(32)}`;
+ const key: AgentApiKeyInfo = {
+ keyId: base64url(12),
+ name,
+ prefix: secret.slice(0, 16),
+ createdBy: ctx.store.f.user.userId,
+ createdAt: new Date().toISOString(),
+ lastUsedAt: null,
+ };
+ settings.keys.push(key);
+ return json({ key: { ...key }, secret } satisfies AgentApiKeyCreateResponse, 201);
+ })
+ .delete("/api/projects/:projectId/agents/:agentId/api/keys/:keyId", (ctx) => {
+ const settings = apiOf(ctx);
+ const kept = settings.keys.filter((k) => k.keyId !== ctx.params.keyId);
+ if (kept.length === settings.keys.length) fail(404, "key_not_found", "No such key.");
+ settings.keys = kept;
+ return empty();
+ })
+ // Try it: the stream a real run sends, scripted (fixtures.ts), whole in one body.
+ .post("/api/projects/:projectId/agents/:agentId/api/try", (ctx) =>
+ raw(
+ amspTryStream(ctx.body, {
+ agent: `${ctx.params.projectId}/${ctx.params.agentId}`,
+ lang: ctx.store.lang,
+ now: Date.now(),
+ }),
+ {
+ "content-type": "text/event-stream; charset=utf-8",
+ },
+ ),
+ );
+
// ---------------------------------------------------------------------------------------------
// Sessions: the list, directories, creation, the row
// ---------------------------------------------------------------------------------------------
diff --git a/packages/ui-gallery/test/mock-api.test.ts b/packages/ui-gallery/test/mock-api.test.ts
index eec077c6..b1135bd9 100644
--- a/packages/ui-gallery/test/mock-api.test.ts
+++ b/packages/ui-gallery/test/mock-api.test.ts
@@ -226,6 +226,70 @@ describe("the mocked API", () => {
expect(store.f.models.models.find((m) => m.isDefault)?.modelId).toBe("claude-sonnet-5");
});
+ it("keeps an Agent's API settings without reaching into an answer the app already holds", async () => {
+ const store = resetStore({ lang: "en", signedIn: true });
+ const project = store.f.project.projectId;
+ const agent = store.f.agents[1]!.agentId;
+ const before = await api.getAgentApi(project, agent);
+ expect(before.api).toMatchObject({ enabled: false, keys: [] });
+ const on = await api.putAgentApi(project, agent, { enabled: true, approvalMode: "read-only" });
+ expect(on.api).toMatchObject({ enabled: true, approvalMode: "read-only" });
+ expect((await api.listAgents(project)).agents[1]!.apiEnabled).toBe(true);
+ const created = await api.createAgentApiKey(project, agent, { name: "ci" });
+ // The app appends the new key to what it read: the earlier answers must not already hold it.
+ expect(before.api.keys).toEqual([]);
+ expect(on.api.keys).toEqual([]);
+ expect(created.secret.startsWith(created.key.prefix)).toBe(true);
+ await api.deleteAgentApiKey(project, agent, created.key.keyId);
+ expect((await api.getAgentApi(project, agent)).api.keys).toEqual([]);
+ });
+
+ it("tells an Agent's API tab when the admin has turned the Agent API off server-wide", async () => {
+ const store = resetStore({ lang: "en", signedIn: true });
+ const project = store.f.project.projectId;
+ const agent = store.f.agents[0]!.agentId;
+ expect((await api.getAgentApi(project, agent)).serverEnabled).toBe(true);
+ await api.adminPutSettings({ agentApiEnabled: false });
+ expect((await api.getAgentApi(project, agent)).serverEnabled).toBe(false);
+ expect((await api.putAgentApi(project, agent, { open: true })).serverEnabled).toBe(false);
+ });
+
+ it("streams a Try run as the try route does: the example run, then a continued one", async () => {
+ const store = resetStore({ lang: "en", signedIn: true });
+ const project = store.f.project.projectId;
+ const agent = store.f.agents[0]!.agentId;
+ /** The body's `data:` payloads, in order. */
+ const payloads = async (res: Response) =>
+ (await res.text())
+ .split("\n\n")
+ .filter((block) => block !== "")
+ .map((block) => block.replace(/^data: /, ""));
+ const typeOf = (payload: string) => (JSON.parse(payload) as { type: string }).type;
+
+ const first = await api.tryAgentApi(project, agent, { input: "What time is it now?" });
+ expect(first.headers.get("content-type")).toMatch(/^text\/event-stream/);
+ const run = await payloads(first);
+ expect(run.at(-1)).toBe("[DONE]");
+ const types = run.slice(0, -1).map(typeOf);
+ expect(types[0]).toBe("run.started");
+ expect(types).toContain("tool_call.done");
+ expect(types).toContain("tool_result.done");
+ expect(types.at(-1)).toBe("run.done");
+
+ const sessionId = (JSON.parse(run[0]!) as { session_id: string }).session_id;
+ const next = await payloads(
+ await api.tryAgentApi(project, agent, { input: "And now?", session_id: sessionId }),
+ );
+ expect(next.slice(0, -1).map(typeOf)).toEqual([
+ "run.started",
+ "request.started",
+ "text.done",
+ "request.done",
+ "run.done",
+ ]);
+ expect(JSON.parse(next[0]!)).toMatchObject({ session_id: sessionId });
+ });
+
it("serves a Workspace file with its version marker through the fetch path", async () => {
const store = resetStore({ lang: "en", signedIn: true });
const session = store.f.sessions[0]!.sessionId;
diff --git a/packages/web/package.json b/packages/web/package.json
index 3d929945..b8df8417 100644
--- a/packages/web/package.json
+++ b/packages/web/package.json
@@ -13,6 +13,7 @@
"test:e2e": "bash e2e/run.sh"
},
"dependencies": {
+ "@lmliheng/amsp": "workspace:*",
"@lmliheng/penguin-core": "workspace:*",
"@lmliheng/penguin-ui": "workspace:*",
"@xterm/addon-clipboard": "^0.1.0",
diff --git a/packages/web/src/api/client.ts b/packages/web/src/api/client.ts
index d36e4e8a..4ed7aa0d 100644
--- a/packages/web/src/api/client.ts
+++ b/packages/web/src/api/client.ts
@@ -74,6 +74,56 @@ export interface ApiFetchMeta {
etag: string | null;
}
+/** The request half every call shares: the method, the session cookie, a JSON body when there is one. */
+function requestInit(options: {
+ method?: string;
+ body?: unknown;
+ signal?: AbortSignal;
+}): RequestInit {
+ return {
+ method: options.method ?? "GET",
+ credentials: "same-origin",
+ ...(options.body !== undefined
+ ? {
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(options.body),
+ }
+ : {}),
+ ...(options.signal !== undefined ? { signal: options.signal } : {}),
+ };
+}
+
+/**
+ * The ApiError a non-2xx response stands for: the server's envelope code and message (or the
+ * generic ones for a body that is not the envelope) and its Retry-After. A 401 from this server
+ * outside the auth endpoints also signs the window out.
+ */
+async function failureOf(
+ response: Response,
+ path: string,
+ target: string | null,
+): Promise<ApiError> {
+ let code = "http_error";
+ let message: string = S.common.unknownError;
+ try {
+ const body = (await response.json()) as { error?: { code?: string; message?: string } };
+ if (body.error?.code) code = body.error.code;
+ if (body.error?.message) message = body.error.message;
+ } catch {
+ // Non-JSON error body: fall back to the default message.
+ }
+ // A 401 from ANOTHER machine is that machine's answer, not this server's: it means we
+ // are not signed in over there, which says nothing about the session here. Treating it
+ // as a local logout is how clicking a remote host in a picker bounced the window to the
+ // login page of a server it was still perfectly signed in to.
+ const fromThisServer = target === null;
+ if (response.status === 401 && fromThisServer && !isAuthEndpoint(path)) onUnauthorized?.();
+ const retryAfter = response.headers.get("retry-after");
+ const retryAfterSeconds =
+ retryAfter !== null && /^\d+$/.test(retryAfter) ? Number(retryAfter) : undefined;
+ return new ApiError(response.status, code, message, retryAfterSeconds);
+}
+
/** Makes an API request; non-2xx responses uniformly throw ApiError; 204/empty body returns undefined. */
export async function apiFetch<T>(path: string, options: ApiFetchOptions = {}): Promise<T> {
return (await apiFetchWithMeta<T>(path, options)).data;
@@ -99,41 +149,12 @@ export async function apiFetchWithMeta<T>(
let response: Response;
try {
- response = await fetch(url, {
- method: options.method ?? "GET",
- credentials: "same-origin",
- ...(options.body !== undefined
- ? {
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(options.body),
- }
- : {}),
- });
+ response = await fetch(url, requestInit(options));
} catch {
throw new ApiError(0, "network_error", S.errors.networkError);
}
- if (!response.ok) {
- let code = "http_error";
- let message: string = S.common.unknownError;
- try {
- const body = (await response.json()) as { error?: { code?: string; message?: string } };
- if (body.error?.code) code = body.error.code;
- if (body.error?.message) message = body.error.message;
- } catch {
- // Non-JSON error body: fall back to the default message.
- }
- // A 401 from ANOTHER machine is that machine's answer, not this server's: it means we
- // are not signed in over there, which says nothing about the session here. Treating it
- // as a local logout is how clicking a remote host in a picker bounced the window to the
- // login page of a server it was still perfectly signed in to.
- const fromThisServer = target === null;
- if (response.status === 401 && fromThisServer && !isAuthEndpoint(path)) onUnauthorized?.();
- const retryAfter = response.headers.get("retry-after");
- const retryAfterSeconds =
- retryAfter !== null && /^\d+$/.test(retryAfter) ? Number(retryAfter) : undefined;
- throw new ApiError(response.status, code, message, retryAfterSeconds);
- }
+ if (!response.ok) throw await failureOf(response, path, target);
const headerDate = Date.parse(response.headers.get("date") ?? "");
const serverNowMs = Number.isFinite(headerDate) ? headerDate : null;
@@ -144,3 +165,34 @@ export async function apiFetchWithMeta<T>(
if (!text) return { data: undefined as T, serverNowMs, etag };
return { data: JSON.parse(text) as T, serverNowMs, etag };
}
+
+export interface ApiFetchStreamOptions {
+ method?: "GET" | "POST";
+ /** JSON request body (auto-serialized with Content-Type: application/json). */
+ body?: unknown;
+ /** Aborting it closes the connection; the call then rejects with the abort's reason. */
+ signal?: AbortSignal;
+}
+
+/**
+ * {@link apiFetch} for an answer read as it arrives (a `text/event-stream`): the same URL and
+ * routing, cookie, JSON body and non-2xx → ApiError mapping, but a 2xx response is handed back
+ * with its body unread. A failed connection is the `network_error` ApiError, except when
+ * `signal` was aborted: that rejects as `fetch` raised it, so the caller can tell a stop from a
+ * failure.
+ */
+export async function apiFetchStream(
+ path: string,
+ options: ApiFetchStreamOptions = {},
+): Promise<Response> {
+ const target = machineForPath(path);
+ let response: Response;
+ try {
+ response = await fetch(apiUrl(path, target), requestInit(options));
+ } catch (err) {
+ if (options.signal?.aborted) throw err;
+ throw new ApiError(0, "network_error", S.errors.networkError);
+ }
+ if (!response.ok) throw await failureOf(response, path, target);
+ return response;
+}
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 45b4f5bd..6ba29bdf 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -9,6 +9,10 @@ import type {
AdminUserCreateRequest,
AdminUserCreateResponse,
AdminUsersResponse,
+ AgentApiKeyCreateRequest,
+ AgentApiKeyCreateResponse,
+ AgentApiResponse,
+ AgentApiUpdateRequest,
AgentConfigResponse,
AgentConfigUpdateRequest,
AgentCreateRequest,
@@ -255,7 +259,8 @@ import type {
DesktopBrowserCommand,
} from "@lmliheng/penguin-server/api";
import type { MCPServerConfig } from "@lmliheng/penguin-core/interfaces";
-import { apiFetch, apiFetchWithMeta } from "./client";
+import type { RunRequest } from "@lmliheng/amsp";
+import { apiFetch, apiFetchStream, apiFetchWithMeta } from "./client";
import { machineForSession, rememberSessionMachine } from "../lib/session-machines";
import { apiUrl } from "../lib/server-context";
import { activityCursorParam } from "../lib/session-grouping";
@@ -801,6 +806,53 @@ export const kernelUpdateAgentConfig = (projectId: string, agentId: string) =>
{ method: "POST" },
);
+// An Agent's public API (the stream itself is AMSP under /api/amsp/v1; these are its settings) ---
+
+const agentApiBase = (projectId: string, agentId: string) =>
+ `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/api`;
+
+/** The Agent's API switch, keyless switch, approval mode and keys (any member may read them). */
+export const getAgentApi = (projectId: string, agentId: string) =>
+ apiFetch<AgentApiResponse>(agentApiBase(projectId, agentId));
+
+/** Changes the given settings and keeps the rest (owner only). */
+export const putAgentApi = (projectId: string, agentId: string, body: AgentApiUpdateRequest) =>
+ apiFetch<AgentApiResponse>(agentApiBase(projectId, agentId), { method: "PUT", body });
+
+/** Mints a key (owner only): the answer is the one place the secret is ever shown. */
+export const createAgentApiKey = (
+ projectId: string,
+ agentId: string,
+ body: AgentApiKeyCreateRequest,
+) =>
+ apiFetch<AgentApiKeyCreateResponse>(`${agentApiBase(projectId, agentId)}/keys`, {
+ method: "POST",
+ body,
+ });
+
+/** Deletes a key for good (owner only): a program presenting it is refused from the next request on. */
+export const deleteAgentApiKey = (projectId: string, agentId: string, keyId: string) =>
+ apiFetch<void>(`${agentApiBase(projectId, agentId)}/keys/${encodeURIComponent(keyId)}`, {
+ method: "DELETE",
+ });
+
+/**
+ * Runs the Agent once through its API for the owner's sign-in (the API tab's Try it): the body is
+ * the public runs route's, and the answer the same AMSP event stream, handed back unread for
+ * `readSse` (or the same JSON refusal, as an ApiError).
+ */
+export const tryAgentApi = (
+ projectId: string,
+ agentId: string,
+ body: RunRequest,
+ opts: { signal?: AbortSignal } = {},
+) =>
+ apiFetchStream(`${agentApiBase(projectId, agentId)}/try`, {
+ method: "POST",
+ body,
+ ...(opts.signal !== undefined ? { signal: opts.signal } : {}),
+ });
+
// Session ---------------------------------------------------------------------
/**
diff --git a/packages/web/src/features/agents/agent-settings-page.tsx b/packages/web/src/features/agents/agent-settings-page.tsx
index 4cbaf51a..56bb0328 100644
--- a/packages/web/src/features/agents/agent-settings-page.tsx
+++ b/packages/web/src/features/agents/agent-settings-page.tsx
@@ -1,5 +1,5 @@
/**
- * Agent settings page: nine tabs —
+ * Agent settings page: ten tabs —
* Overview (name/description form + two ruled sections in the skills import modal's
* family: Agent State — State version, snapshot export-import and the copyable State
* path — and Kernel — the defaults generation with its update / restore-defaults
@@ -7,7 +7,7 @@
* reference), Runtime (max_turns, model.*, compaction.*), Tools (editable built-in
* tools table + the MCP Server form, mcp-servers-section.tsx), Skills (skills-tab.tsx),
* Hooks (hooks-tab.tsx), Memory (memory-tab.tsx), Vault (vault-tab.tsx), Schedule
- * (schedules-tab.tsx).
+ * (schedules-tab.tsx), API (api-tab.tsx: the Agent's public API, kept by this server).
* Save = PUT config (sends only the changed keys; YAML comments are preserved
* server-side).
*/
@@ -64,6 +64,7 @@ import { MemoryTab } from "./memory-tab";
import { kernelTabLabel } from "./kernel-labels";
import { VaultTab } from "./vault-tab";
import { SchedulesTab } from "./schedules-tab";
+import { ApiTab } from "./api-tab";
import { McpServersSection } from "./mcp-servers-section";
import { SNAPSHOT_ACCEPT, SNAPSHOT_BUTTON_CLASS, fileToBase64 } from "./snapshot-file";
import { thinkingLevelOptionsFor } from "../chat/thinking-level";
@@ -77,7 +78,8 @@ type TabKey =
| "hooks"
| "memory"
| "vault"
- | "schedules";
+ | "schedules"
+ | "api";
/**
* Dropdown rows from a dictionary's [value, description] pairs (exported for unit tests).
@@ -137,6 +139,7 @@ export function AgentSettingsPage() {
{ key: "memory", label: S.agent.tabMemory },
{ key: "vault", label: S.agent.tabVault },
{ key: "schedules", label: S.agent.tabSchedules },
+ { key: "api", label: S.agent.tabApi },
] as const;
const navigate = useNavigate();
const params = useParams<{ agentId: string }>();
@@ -314,6 +317,13 @@ export function AgentSettingsPage() {
{tab === "hooks" && <HooksTab agentId={agentId} onConfigChanged={refreshConfig} />}
{tab === "vault" && <VaultTab agentId={agentId} onConfigChanged={refreshConfig} />}
{tab === "schedules" && <SchedulesTab agentId={agentId} onConfigChanged={refreshConfig} />}
+ {tab === "api" && (
+ <ApiTab
+ projectId={projectId}
+ agentId={agentId}
+ isOwner={currentProject?.role === "owner"}
+ />
+ )}
</div>
</PageFrame>
);
diff --git a/packages/web/src/features/agents/agents-page.tsx b/packages/web/src/features/agents/agents-page.tsx
index 691b1ec0..d1081c71 100644
--- a/packages/web/src/features/agents/agents-page.tsx
+++ b/packages/web/src/features/agents/agents-page.tsx
@@ -119,6 +119,21 @@ const STAT_LINK_CLASS =
"inline-flex shrink-0 cursor-pointer items-center gap-1 tabular-nums " +
"transition-colors duration-150 hover:text-gray-800 dark:hover:text-gray-200";
+/**
+ * The mark an Agent whose public API is on carries after its name: the plug the API wears
+ * everywhere (the sidebar's Background rows included), with its meaning in the tooltip and for
+ * screen readers. An Agent with the API off carries nothing.
+ */
+export function AgentApiMark({ enabled }: { enabled: boolean }) {
+ if (!enabled) return null;
+ return (
+ <span data-tooltip={S.agent.apiOn} className="shrink-0 text-fg-subtle">
+ <GlyphIcon d={ICONS.plug} size={ICON_SIZE.inlineGlyph} />
+ <span className="sr-only">{S.agent.apiOn}</span>
+ </span>
+ );
+}
+
/**
* The library's plugins as picker rows. A row is a Skill's metadata, which a plugin's manifest
* already carries (name, descriptions, icon, version); a plugin without an icon.svg draws the
@@ -585,6 +600,7 @@ export function AgentsPage() {
{S.chat.machineTag(machineName)}
</span>
)}
+ <AgentApiMark enabled={a.apiEnabled} />
<span className="hidden shrink-0 font-mono text-xs text-gray-400 md:inline dark:text-gray-500">
{a.agentId}
</span>
diff --git a/packages/web/src/features/agents/api-tab.tsx b/packages/web/src/features/agents/api-tab.tsx
new file mode 100644
index 00000000..3c347131
--- /dev/null
+++ b/packages/web/src/features/agents/api-tab.tsx
@@ -0,0 +1,623 @@
+/**
+ * Agent settings page "API" tab: whether external programs may talk to this Agent over its public
+ * API (the AMSP stream under /api/amsp/v1), the approval mode its API conversations start with,
+ * the address and id a program needs, the keys, and two examples that call it.
+ *
+ * Everything here is this server's, kept in its database — not in the Agent State, not in the
+ * synced Project file — so the Agent can neither expose itself nor loosen its own approvals. Any
+ * member reads it; only the Project owner changes it. Each control applies on the flip, with no
+ * Save: turning the API on writes at once, while turning it off and deleting a key ask first,
+ * because a program using them is refused from then on. A new key's secret exists only in the
+ * create response: it is shown once, in a panel with its copy button, until Done, and afterwards
+ * the list names the key by its prefix alone.
+ *
+ * The admin's server-wide switch (Settings › Server › Agent API) overrides every Agent: when it is
+ * off the switch here is disabled and says so, and nothing is lost. The tab's own read carries that
+ * switch (`serverEnabled`), so every member sees it, not only an admin.
+ *
+ * The owner's tab ends with Try it (api-try-panel.tsx): one real API run on the owner's sign-in,
+ * its stream shown as a program would receive it.
+ */
+import { useCallback, useEffect, useState } from "react";
+import type { KeyboardEvent } from "react";
+import type {
+ AgentApiKeyInfo,
+ AgentApiResponse,
+ AgentApiSettings,
+ AgentApiUpdateRequest,
+ ApprovalMode,
+} from "@lmliheng/penguin-server/api";
+import {
+ Button,
+ CodeBlock,
+ ConfirmModal,
+ CopyButton,
+ GlyphIcon,
+ ICON_SIZE,
+ ICONS,
+ Input,
+ RuledSection,
+ Select,
+ SkeletonList,
+ ToggleRow,
+ toastError,
+} from "@lmliheng/penguin-ui";
+import * as api from "../../api/endpoints";
+import { apiErrorText } from "../../lib/api-error";
+import { formatDateTime } from "../../lib/format";
+import { S } from "../../lib/strings";
+import { toneInk } from "../../lib/tone";
+import { useProject } from "../../state/project";
+import { APPROVAL_MODES } from "../chat/approval-mode";
+import { ApiTryPanel } from "./api-try-panel";
+
+/** The public API's root on the server this page was served from. */
+export function agentApiBaseUrl(origin: string): string {
+ return `${origin}/api/amsp/v1`;
+}
+
+/** How the API names an Agent: the Project and the Agent, qualified. */
+export function agentApiRef(projectId: string, agentId: string): string {
+ return `${projectId}/${agentId}`;
+}
+
+/** A curl call and an SDK call against this Agent, with the key left as an environment variable. */
+export function agentApiExamples(baseUrl: string, agentRef: string): { curl: string; sdk: string } {
+ const curl = [
+ `curl -N ${baseUrl}/agents/${agentRef}/runs \\`,
+ ` -H "Authorization: Bearer $ADELIE_AGENT_KEY" \\`,
+ ` -H "Content-Type: application/json" \\`,
+ ` -d '{"input":"Hello"}'`,
+ ].join("\n");
+ const sdk = [
+ `import { AgentClient } from "@lmliheng/amsp";`,
+ ``,
+ `const client = new AgentClient({`,
+ ` baseUrl: "${baseUrl}",`,
+ ` agent: "${agentRef}",`,
+ ` apiKey: process.env.ADELIE_AGENT_KEY,`,
+ `});`,
+ ``,
+ `const result = await client.ask({ input: "Hello" });`,
+ `console.log(result.text);`,
+ ].join("\n");
+ return { curl, sdk };
+}
+
+/** Writes the Agent's API off. Reached only through the confirm. */
+const switchOffAgentApi = (projectId: string, agentId: string): Promise<AgentApiResponse> =>
+ api.putAgentApi(projectId, agentId, { enabled: false });
+
+/** Opens the Agent to callers without a key. Reached only through the confirm. */
+const switchOnKeyless = (projectId: string, agentId: string): Promise<AgentApiResponse> =>
+ api.putAgentApi(projectId, agentId, { open: true });
+
+/**
+ * The warning before keyless access goes on, in the danger tone: once it is on, anything that
+ * can reach the server talks to the Agent on the Project's models and credentials. Answered yes,
+ * it says the write began, writes the switch on and hands on the outcome. Turning it off needs
+ * no question.
+ */
+export function KeylessOnConfirm({
+ open,
+ projectId,
+ agentId,
+ onClose,
+ onWriting,
+ onSettled,
+}: {
+ open: boolean;
+ projectId: string;
+ agentId: string;
+ onClose: () => void;
+ onWriting: () => void;
+ onSettled: (outcome: AgentApiResponse | { error: unknown }) => void;
+}) {
+ return (
+ <ConfirmModal
+ open={open}
+ title={S.agent.apiOpenTitle}
+ onClose={onClose}
+ onConfirm={() => {
+ onClose();
+ onWriting();
+ switchOnKeyless(projectId, agentId).then(
+ (res) => onSettled(res),
+ (error: unknown) => onSettled({ error }),
+ );
+ }}
+ confirmLabel={S.agent.apiOpenConfirm}
+ cancelLabel={S.common.cancel}
+ >
+ <p className="text-sm text-fg-muted">{S.agent.apiOpenBody}</p>
+ </ConfirmModal>
+ );
+}
+
+/** Deletes one key. Reached only through the confirm. */
+const deleteKey = (projectId: string, agentId: string, keyId: string): Promise<void> =>
+ api.deleteAgentApiKey(projectId, agentId, keyId);
+
+/**
+ * The question before the Agent's API goes off, in the danger tone. Answered yes, it says the
+ * write began, writes the switch off and hands on the outcome: what the server stored, or the
+ * failure.
+ */
+export function AgentApiOffConfirm({
+ open,
+ projectId,
+ agentId,
+ onClose,
+ onWriting,
+ onSettled,
+}: {
+ open: boolean;
+ projectId: string;
+ agentId: string;
+ onClose: () => void;
+ onWriting: () => void;
+ onSettled: (outcome: AgentApiResponse | { error: unknown }) => void;
+}) {
+ return (
+ <ConfirmModal
+ open={open}
+ title={S.agent.apiOffTitle}
+ onClose={onClose}
+ onConfirm={() => {
+ onClose();
+ onWriting();
+ switchOffAgentApi(projectId, agentId).then(
+ (res) => onSettled(res),
+ (error: unknown) => onSettled({ error }),
+ );
+ }}
+ confirmLabel={S.agent.apiOff}
+ cancelLabel={S.common.cancel}
+ >
+ <p className="text-sm text-fg-muted">{S.agent.apiOffBody}</p>
+ </ConfirmModal>
+ );
+}
+
+/**
+ * The question before a key is deleted, naming it, in the danger tone. Answered yes, it deletes
+ * the key and hands on which one went; a refused delete says why and hands on nothing.
+ */
+export function DeleteKeyConfirm({
+ record,
+ projectId,
+ agentId,
+ onClose,
+ onDeleted,
+}: {
+ /** The key in question; null keeps the dialog closed. */
+ record: AgentApiKeyInfo | null;
+ projectId: string;
+ agentId: string;
+ onClose: () => void;
+ onDeleted: (keyId: string) => void;
+}) {
+ return (
+ <ConfirmModal
+ open={record !== null}
+ title={S.agent.apiDeleteKey}
+ onClose={onClose}
+ onConfirm={() => {
+ if (record === null) return;
+ onClose();
+ deleteKey(projectId, agentId, record.keyId).then(
+ () => onDeleted(record.keyId),
+ (error: unknown) => toastError(apiErrorText(error)),
+ );
+ }}
+ confirmLabel={S.common.delete}
+ cancelLabel={S.common.cancel}
+ >
+ <p className="text-sm text-fg-muted">
+ {record !== null ? S.agent.apiDeleteKeyBody(record.name) : ""}
+ </p>
+ </ConfirmModal>
+ );
+}
+
+/** One labelled value a program needs, set in mono with its copy button. */
+function ConnectionRow({ label, value }: { label: string; value: string }) {
+ return (
+ <div>
+ <p className="text-xs font-medium text-fg-muted">{label}</p>
+ <div className="flex items-start gap-1.5">
+ <span className="min-w-0 flex-1 break-all font-mono text-sm font-semibold leading-5">
+ {value}
+ </span>
+ <CopyButton text={value} label={S.agent.apiCopy(label)} size="sm" className="shrink-0" />
+ </div>
+ </div>
+ );
+}
+
+/** A just-created key's secret: the one time it is on screen, with its copy button and Done. */
+export function OneTimeKey({ secret, onDone }: { secret: string; onDone: () => void }) {
+ return (
+ <div className="mb-3 space-y-2 rounded-lg border border-line px-4 py-3">
+ <div className="flex items-start gap-1.5">
+ <span className="min-w-0 flex-1 break-all font-mono text-sm font-semibold leading-5">
+ {secret}
+ </span>
+ <CopyButton text={secret} label={S.agent.apiCopySecret} size="sm" className="shrink-0" />
+ </div>
+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
+ <p className={`text-xs ${toneInk.attention}`}>{S.agent.apiKeyShownOnce}</p>
+ <Button size="sm" onClick={onDone}>
+ {S.agent.apiKeyDone}
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+/** One key: its name, the prefix it is told apart by, when it was made and last used. */
+function KeyRow({
+ record,
+ canDelete,
+ onDelete,
+}: {
+ record: AgentApiKeyInfo;
+ canDelete: boolean;
+ onDelete: (record: AgentApiKeyInfo) => void;
+}) {
+ return (
+ <li data-testid="api-key" className="flex items-center gap-3 py-2.5">
+ <div className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-4 gap-y-1">
+ <span className="min-w-0 truncate text-sm font-medium">{record.name}</span>
+ <span className="font-mono text-xs text-fg-muted">{record.prefix}…</span>
+ <span className="text-xs">
+ <span className="text-fg-muted">{S.agent.apiKeyCreated}</span>{" "}
+ <span className="font-semibold tabular-nums">{formatDateTime(record.createdAt)}</span>
+ </span>
+ <span className="text-xs">
+ <span className="text-fg-muted">{S.agent.apiKeyLastUsed}</span>{" "}
+ <span className="font-semibold tabular-nums">
+ {record.lastUsedAt === null ? S.agent.apiKeyNever : formatDateTime(record.lastUsedAt)}
+ </span>
+ </span>
+ </div>
+ {canDelete && (
+ <button
+ type="button"
+ data-tooltip={S.agent.apiDeleteKey}
+ aria-label={`${S.agent.apiDeleteKey} ${record.name}`}
+ onClick={() => onDelete(record)}
+ className="inline-flex size-6 shrink-0 items-center justify-center rounded text-fg-subtle transition-colors duration-150 hover:text-tone-danger-fg"
+ >
+ <GlyphIcon d={ICONS.trash} size={ICON_SIZE.rowLead} />
+ </button>
+ )}
+ </li>
+ );
+}
+
+export interface ApiTabViewProps {
+ projectId: string;
+ agentId: string;
+ settings: AgentApiSettings;
+ /** The admin's server-wide switch, as the tab's own read reports it to every member. */
+ serverEnabled: boolean;
+ isOwner: boolean;
+ busy: boolean;
+ baseUrl: string;
+ agentRef: string;
+ /** The name typed for a new key; null while no key is being made. */
+ draftName: string | null;
+ draftError?: string;
+ /** A just-created key's secret, until Done; null otherwise. */
+ secret: string | null;
+ onToggleEnabled: (next: boolean) => void;
+ onApprovalMode: (mode: ApprovalMode) => void;
+ onToggleOpen: (next: boolean) => void;
+ onStartKey: () => void;
+ onDraftName: (name: string) => void;
+ onCreateKey: () => void;
+ onCancelKey: () => void;
+ onSecretDone: () => void;
+ onDeleteKey: (record: AgentApiKeyInfo) => void;
+}
+
+/** The tab as it reads for one state of the settings: no state of its own. */
+export function ApiTabView(p: ApiTabViewProps) {
+ const serverOff = !p.serverEnabled;
+ const examples = agentApiExamples(p.baseUrl, p.agentRef);
+ const onDraftKey = (e: KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === "Enter") p.onCreateKey();
+ else if (e.key === "Escape") p.onCancelKey();
+ };
+ return (
+ <div className="space-y-6">
+ <div className="space-y-2">
+ <ToggleRow
+ variant="card"
+ label={S.agent.apiEnable}
+ info={S.agent.apiEnableHint}
+ checked={p.settings.enabled}
+ onChange={p.onToggleEnabled}
+ disabled={!p.isOwner || serverOff || p.busy}
+ />
+ {serverOff && <p className="text-xs text-fg-muted">{S.agent.apiAdminOff}</p>}
+ {!p.isOwner && <p className="text-xs text-fg-muted">{S.agent.apiOwnerOnly}</p>}
+ </div>
+
+ {p.settings.enabled && (
+ <>
+ {/* A width on a box around the field: the select's own w-full would beat one passed in. */}
+ <div className="max-w-sm">
+ <Select
+ size="sm"
+ label={S.agent.apiApprovalMode}
+ hint={S.agent.apiApprovalModeHint}
+ value={p.settings.approvalMode}
+ disabled={!p.isOwner || p.busy}
+ onChange={(e) => {
+ const mode = APPROVAL_MODES.find((m) => m === e.target.value);
+ if (mode !== undefined) p.onApprovalMode(mode);
+ }}
+ >
+ {APPROVAL_MODES.map((mode) => (
+ <option key={mode} value={mode}>
+ {S.chat.approvalModeNames[mode] ?? mode}
+ </option>
+ ))}
+ </Select>
+ </div>
+
+ <RuledSection title={S.agent.apiConnection}>
+ <div className="space-y-3">
+ <ConnectionRow label={S.agent.apiBaseUrl} value={p.baseUrl} />
+ <ConnectionRow label={S.agent.apiAgentId} value={p.agentRef} />
+ </div>
+ </RuledSection>
+
+ <RuledSection
+ title={S.agent.apiKeys}
+ count={p.settings.keys.length}
+ actions={
+ p.isOwner && p.draftName === null ? (
+ <Button size="sm" disabled={p.busy} onClick={p.onStartKey}>
+ {S.agent.apiNewKey}
+ </Button>
+ ) : undefined
+ }
+ >
+ {p.draftName !== null && (
+ <div className="mb-3 flex flex-wrap items-start gap-2">
+ <div className="min-w-0 flex-1 sm:max-w-xs">
+ <Input
+ size="sm"
+ aria-label={S.agent.apiKeyName}
+ placeholder={S.agent.apiKeyName}
+ value={p.draftName}
+ maxLength={64}
+ error={p.draftError}
+ autoFocus
+ onChange={(e) => p.onDraftName(e.target.value)}
+ onKeyDown={onDraftKey}
+ />
+ </div>
+ <Button size="sm" variant="primary" loading={p.busy} onClick={p.onCreateKey}>
+ {S.common.create}
+ </Button>
+ <Button size="sm" variant="ghost" onClick={p.onCancelKey}>
+ {S.common.cancel}
+ </Button>
+ </div>
+ )}
+ {p.secret !== null && <OneTimeKey secret={p.secret} onDone={p.onSecretDone} />}
+ {p.settings.keys.length === 0 ? (
+ <p className="text-xs text-fg-muted">{S.agent.apiKeysEmpty}</p>
+ ) : (
+ <ul className="divide-y divide-line-muted">
+ {p.settings.keys.map((record) => (
+ <KeyRow
+ key={record.keyId}
+ record={record}
+ canDelete={p.isOwner}
+ onDelete={p.onDeleteKey}
+ />
+ ))}
+ </ul>
+ )}
+ <div className="mt-4 space-y-1">
+ <ToggleRow
+ variant="plain"
+ label={S.agent.apiOpen}
+ checked={p.settings.open}
+ onChange={p.onToggleOpen}
+ disabled={!p.isOwner || p.busy}
+ />
+ <p className={`text-xs ${toneInk.attention}`}>{S.agent.apiOpenHint}</p>
+ </div>
+ </RuledSection>
+
+ <RuledSection title={S.agent.apiExamples}>
+ <CodeBlock language="bash" code={examples.curl} />
+ <CodeBlock language="typescript" code={examples.sdk} />
+ </RuledSection>
+
+ {p.isOwner && (
+ <ApiTryPanel
+ // Another Agent's tab starts its own Try it: no Session carried over.
+ key={p.agentRef}
+ projectId={p.projectId}
+ agentId={p.agentId}
+ disabledReason={serverOff ? S.agent.apiAdminOff : undefined}
+ />
+ )}
+ </>
+ )}
+ </div>
+ );
+}
+
+export function ApiTab({
+ projectId,
+ agentId,
+ isOwner,
+}: {
+ projectId: string;
+ agentId: string;
+ isOwner: boolean;
+}) {
+ const { reloadAgents } = useProject();
+ const [settings, setSettings] = useState<AgentApiSettings | null>(null);
+ // Only the initial load failure renders inline; writes report via toast.
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [serverEnabled, setServerEnabled] = useState(true);
+ const [busy, setBusy] = useState(false);
+ const [confirmOff, setConfirmOff] = useState(false);
+ const [confirmKeyless, setConfirmKeyless] = useState(false);
+ const [deleting, setDeleting] = useState<AgentApiKeyInfo | null>(null);
+ const [draftName, setDraftName] = useState<string | null>(null);
+ const [draftError, setDraftError] = useState<string | undefined>(undefined);
+ const [secret, setSecret] = useState<string | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ setSettings(null);
+ setLoadError(null);
+ api.getAgentApi(projectId, agentId).then(
+ (res) => {
+ if (cancelled) return;
+ setSettings(res.api);
+ setServerEnabled(res.serverEnabled);
+ },
+ (e: unknown) => {
+ if (!cancelled) setLoadError(apiErrorText(e));
+ },
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, [projectId, agentId]);
+
+ /** One settings write: the stored answer replaces the view, a failure says why. */
+ const write = useCallback(
+ async (patch: AgentApiUpdateRequest) => {
+ setBusy(true);
+ try {
+ const res = await api.putAgentApi(projectId, agentId, patch);
+ setSettings(res.api);
+ setServerEnabled(res.serverEnabled);
+ // The Agents list marks an Agent whose API is on.
+ if (patch.enabled !== undefined) void reloadAgents();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ },
+ [projectId, agentId, reloadAgents],
+ );
+
+ const createKey = async () => {
+ const name = (draftName ?? "").trim();
+ if (name === "") {
+ setDraftError(S.common.requiredField);
+ return;
+ }
+ setBusy(true);
+ try {
+ const res = await api.createAgentApiKey(projectId, agentId, { name });
+ setSettings((prev) => (prev === null ? prev : { ...prev, keys: [...prev.keys, res.key] }));
+ setSecret(res.secret);
+ setDraftName(null);
+ setDraftError(undefined);
+ } catch (e) {
+ setDraftError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ if (loadError !== null) return <p className={`text-sm ${toneInk.danger}`}>{loadError}</p>;
+ if (settings === null) return <SkeletonList rows={3} />;
+
+ return (
+ <>
+ <ApiTabView
+ projectId={projectId}
+ agentId={agentId}
+ settings={settings}
+ serverEnabled={serverEnabled}
+ isOwner={isOwner}
+ busy={busy}
+ baseUrl={agentApiBaseUrl(window.location.origin)}
+ agentRef={agentApiRef(projectId, agentId)}
+ draftName={draftName}
+ {...(draftError !== undefined ? { draftError } : {})}
+ secret={secret}
+ onToggleEnabled={(next) => {
+ if (next) void write({ enabled: true });
+ else setConfirmOff(true);
+ }}
+ onApprovalMode={(approvalMode) => void write({ approvalMode })}
+ onToggleOpen={(open) => {
+ if (open) setConfirmKeyless(true);
+ else void write({ open: false });
+ }}
+ onStartKey={() => {
+ setDraftName("");
+ setDraftError(undefined);
+ }}
+ onDraftName={(name) => {
+ setDraftName(name);
+ setDraftError(undefined);
+ }}
+ onCreateKey={() => void createKey()}
+ onCancelKey={() => {
+ setDraftName(null);
+ setDraftError(undefined);
+ }}
+ onSecretDone={() => setSecret(null)}
+ onDeleteKey={setDeleting}
+ />
+ <AgentApiOffConfirm
+ open={confirmOff}
+ projectId={projectId}
+ agentId={agentId}
+ onClose={() => setConfirmOff(false)}
+ onWriting={() => setBusy(true)}
+ onSettled={(outcome) => {
+ if ("api" in outcome) {
+ setSettings(outcome.api);
+ setServerEnabled(outcome.serverEnabled);
+ void reloadAgents();
+ } else toastError(apiErrorText(outcome.error));
+ setBusy(false);
+ }}
+ />
+ <KeylessOnConfirm
+ open={confirmKeyless}
+ projectId={projectId}
+ agentId={agentId}
+ onClose={() => setConfirmKeyless(false)}
+ onWriting={() => setBusy(true)}
+ onSettled={(outcome) => {
+ if ("api" in outcome) {
+ setSettings(outcome.api);
+ setServerEnabled(outcome.serverEnabled);
+ } else toastError(apiErrorText(outcome.error));
+ setBusy(false);
+ }}
+ />
+ <DeleteKeyConfirm
+ record={deleting}
+ projectId={projectId}
+ agentId={agentId}
+ onClose={() => setDeleting(null)}
+ onDeleted={(keyId) =>
+ setSettings((prev) =>
+ prev === null ? prev : { ...prev, keys: prev.keys.filter((k) => k.keyId !== keyId) },
+ )
+ }
+ />
+ </>
+ );
+}
diff --git a/packages/web/src/features/agents/api-try-log.ts b/packages/web/src/features/agents/api-try-log.ts
new file mode 100644
index 00000000..564e83fc
--- /dev/null
+++ b/packages/web/src/features/agents/api-try-log.ts
@@ -0,0 +1,566 @@
+/**
+ * The API tab's Try it, without React: the state of one panel, the reducer that folds a run's
+ * stream into it, and the async driver that feeds it.
+ *
+ * A run is the Agent API's own run, sent through the owner's try route (`tryAgentApi`) and read
+ * with the SDK's `readSse`, so the panel sees exactly the `data:` payloads a program would. Every
+ * payload is kept verbatim: the raw view prints them back, one numbered line each. The rendered
+ * view reads the same payloads as rows, one per item or event:
+ *
+ * - An item's fragments and its complete form are one row (`text`, `thinking`, `tool_call`,
+ * `tool_result`, `summary`, the inline media). While fragments arrive the row shows them joined;
+ * once the `.done` arrives it shows the `.done`'s content instead. The two are the same item, so
+ * nothing compares them: the latest is what shows. Fragments find their row by the item they
+ * belong to — a tool call or result by its `tool_call_id`, since results interleave — so a row
+ * keeps its place when other rows come between its fragments.
+ * - Every other event is a row of its own, with its key fields.
+ *
+ * `run.done` gives the status strip, folded by the SDK's `RunCollector` as a program's
+ * `result()` would be. The Session id that `run.started` names stays after the run, so the next
+ * run continues the conversation, the way a program passes `session_id`; New conversation
+ * forgets it.
+ */
+import { readSse, RunCollector } from "@lmliheng/amsp";
+import type { AmspError, AmspEvent, RunRequest, RunResult, TokenCounts } from "@lmliheng/amsp";
+import { ApiError } from "../../api/client";
+import * as api from "../../api/endpoints";
+
+/** Where a one-line value is cut, so one long argument string does not take the row. */
+const CUT = 120;
+
+const cut = (text: string): string => (text.length > CUT ? `${text.slice(0, CUT)}…` : text);
+
+/** One value of an event row: the wire name it is known by (if any) and the value. */
+export interface TryField {
+ name?: string;
+ value: string;
+ /** Free text (a message, a list of names) rather than a value to pick out. */
+ quiet?: boolean;
+}
+
+/** A row standing for one item: its fragments, its complete form, or both. */
+export interface TryItemRow {
+ kind: "item";
+ /** The row's place in the rendered view, from 0; it never moves. */
+ id: number;
+ /** What the item is: its events' type before `.delta` / `.done` (`text`, `tool_call`, …). */
+ item: string;
+ /** The item its fragments and `.done` belong to. */
+ key: string;
+ /** Fragments arrived and nothing has said the item is complete yet. */
+ open: boolean;
+ /**
+ * The content so far: the fragments joined, or the `.done`'s own once it came. A text, a
+ * thinking or a summary's text; a tool call's arguments; a tool result's output.
+ */
+ text: string;
+ /** A tool call's tool. */
+ name?: string;
+ /** Inline media and image inputs: what they are and how big, never the bytes themselves. */
+ media?: { mime: string; bytes: number };
+ /** How many images a tool result carries. */
+ images?: number;
+ /** What sets the item apart from the plain case: a text's sender, a stop other than completed. */
+ tags: string[];
+ /** The child Session chain it came from, outer→inner; absent for the main Session. */
+ origin?: string;
+}
+
+/** A row standing for one event that is not part of an item. */
+export interface TryEventRow {
+ kind: "event";
+ id: number;
+ /** The event's `type`; `?` for a payload that is not an AMSP event. */
+ type: string;
+ fields: TryField[];
+ /** On `approval.requested`: the call it asks about, and whether an answer is still open. */
+ approval?: { toolCallId: string; pending: boolean };
+ origin?: string;
+}
+
+export type TryRow = TryItemRow | TryEventRow;
+
+/** The label a row carries in the rendered view: the item's kind, or the event's type. */
+export const rowLabel = (row: TryRow): string => (row.kind === "item" ? row.item : row.type);
+
+/** The kinds of item whose events merge into one row. */
+const ITEMS = new Set([
+ "text",
+ "thinking",
+ "tool_call",
+ "tool_result",
+ "summary",
+ "inline_data",
+ "inline_thinking",
+ "image_url",
+]);
+
+/** The field that carries an item's text, on its fragments and on its `.done` alike. */
+const TEXT_FIELD: Record<string, string> = {
+ text: "text",
+ thinking: "thinking",
+ summary: "text",
+ tool_call: "arguments",
+ tool_result: "output",
+};
+
+/** The payload as an AMSP event, or null when it is not one (not JSON, or no `type`). */
+function parseEvent(payload: string): AmspEvent | null {
+ try {
+ const value: unknown = JSON.parse(payload);
+ return value !== null &&
+ typeof value === "object" &&
+ typeof (value as { type?: unknown }).type === "string"
+ ? (value as AmspEvent)
+ : null;
+ } catch {
+ return null;
+ }
+}
+
+const str = (value: unknown): string => (typeof value === "string" ? value : "");
+
+/** The size of base64 data once decoded. */
+function base64Bytes(data: string): number {
+ const body = data.replace(/[\s=]/g, "");
+ return Math.floor((body.length * 3) / 4);
+}
+
+/** A `data:` URL's media type and decoded size; null for any other URL. */
+function dataUrlMedia(url: string): { mime: string; bytes: number } | null {
+ const match = /^data:([^;,]*)(;base64)?,/.exec(url);
+ if (match === null) return null;
+ const body = url.slice(match[0].length);
+ return {
+ mime: match[1] || "text/plain",
+ bytes: match[2] !== undefined ? base64Bytes(body) : body.length,
+ };
+}
+
+const originOf = (ev: AmspEvent): string | undefined =>
+ ev.origin !== undefined && ev.origin.length > 0 ? ev.origin.join("/") : undefined;
+
+/** The row an item's event belongs to, as it reads after that event. */
+function itemRow(
+ prev: TryItemRow | undefined,
+ id: number,
+ ev: AmspEvent,
+ item: string,
+ done: boolean,
+) {
+ const f = ev as unknown as Record<string, unknown>;
+ const field = TEXT_FIELD[item];
+ const piece = field !== undefined ? str(f[field]) : "";
+ const origin = originOf(ev);
+ const row: TryItemRow = prev
+ ? { ...prev, tags: [...prev.tags] }
+ : {
+ kind: "item",
+ id,
+ item,
+ key: itemKey(ev, item),
+ open: true,
+ text: "",
+ tags: [],
+ ...(origin !== undefined ? { origin } : {}),
+ };
+ // A complete item replaces whatever its fragments said; a fragment adds to it.
+ row.text = done ? piece : row.text + piece;
+ if (item === "tool_call") {
+ const name = str(f.name);
+ if (done || row.name === undefined || row.name === "") row.name = name;
+ }
+ // A result's images are never fragmented: whichever event carries them carries the whole set.
+ if (Array.isArray(f.images)) row.images = f.images.length;
+ if (item === "inline_data" || item === "inline_thinking") {
+ const bytes = base64Bytes(str(f.data));
+ row.media = {
+ mime: str(f.mime_type) || row.media?.mime || "",
+ bytes: done ? bytes : (row.media?.bytes ?? 0) + bytes,
+ };
+ }
+ if (item === "image_url") {
+ const url = str(f.image_url);
+ const media = dataUrlMedia(url);
+ if (media !== null) row.media = media;
+ else row.text = url;
+ }
+ if (done) {
+ row.open = false;
+ // An image input is the user's by definition; elsewhere a user-role item is the exception.
+ if (f.role === "user" && item !== "image_url") row.tags.push(str(f.sender) || "user");
+ const stop = str(f.stop_reason);
+ if (stop !== "" && stop !== "completed") row.tags.push(stop);
+ }
+ return row;
+}
+
+/** Which item an event belongs to: its kind, role, tool call and Session. */
+function itemKey(ev: AmspEvent, item: string): string {
+ const f = ev as unknown as Record<string, unknown>;
+ return [item, str(f.role), str(f.tool_call_id), originOf(ev) ?? ""].join(" ");
+}
+
+const tokens = (usage: TokenCounts | null): TryField[] =>
+ usage === null
+ ? []
+ : [
+ { name: "output", value: String(usage.output) },
+ { name: "total", value: String(usage.total) },
+ ];
+
+const failure = (error: AmspError | undefined): TryField[] =>
+ error === undefined ? [] : [{ value: error.code }, { value: error.message, quiet: true }];
+
+/** The key fields of an event that stands alone, in the order its row shows them. */
+export function eventFields(ev: AmspEvent): TryField[] {
+ switch (ev.type) {
+ case "run.started":
+ return [{ value: ev.session_id }];
+ case "run.done":
+ return [
+ { value: ev.status },
+ { name: "requests", value: String(ev.requests) },
+ ...tokens(ev.usage),
+ ...failure(ev.error),
+ ];
+ case "context.opened":
+ return [
+ { value: `${ev.provider}/${ev.model_id}` },
+ { name: "context_window", value: String(ev.context_window) },
+ ];
+ case "mcp_connect.started":
+ return [{ value: ev.servers.join(", ") }];
+ case "mcp_connect.done":
+ return [
+ { value: ev.status },
+ ...ev.results.map((r) => ({ name: r.server, value: r.status })),
+ ...failure(ev.error),
+ ];
+ case "tools.ready":
+ return [
+ { value: String(ev.tools.length) },
+ { value: ev.tools.map((t) => t.name).join(", "), quiet: true },
+ ];
+ case "request.started":
+ return [{ value: `#${ev.request}` }];
+ case "request.done":
+ return [
+ { value: `#${ev.request}` },
+ { value: ev.status },
+ ...tokens(ev.usage),
+ ...(ev.attempt !== undefined ? [{ name: "attempt", value: String(ev.attempt) }] : []),
+ ...(ev.retry_in_ms !== undefined
+ ? [{ name: "retry_in_ms", value: String(ev.retry_in_ms) }]
+ : []),
+ ...failure(ev.error),
+ ];
+ case "approval.requested":
+ return [{ value: ev.tool_call.name }, { value: cut(ev.tool_call.arguments), quiet: true }];
+ case "approval.decided":
+ return [{ value: ev.decision }];
+ case "compaction.started":
+ return [
+ { value: ev.reason },
+ { name: "mode", value: ev.mode },
+ { name: "context", value: String(ev.context) },
+ { name: "turns", value: String(ev.turns) },
+ ];
+ case "compaction.done":
+ return [
+ { value: ev.reason },
+ { name: "mode", value: ev.mode },
+ { value: ev.status },
+ ...tokens(ev.usage),
+ ...failure(ev.error),
+ ];
+ case "hook.fired":
+ return [
+ { value: ev.hook },
+ { value: ev.name },
+ ...(ev.decision !== undefined ? [{ name: "decision", value: ev.decision }] : []),
+ ...(ev.reason !== undefined ? [{ value: ev.reason, quiet: true }] : []),
+ ];
+ default: {
+ // A type this panel does not know (the protocol adds them within /v1): what it carries.
+ const rest = Object.fromEntries(
+ Object.entries(ev).filter(([field]) => field !== "type" && field !== "at"),
+ );
+ return [{ value: cut(JSON.stringify(rest)), quiet: true }];
+ }
+ }
+}
+
+/** The rows with every open item that `close` picks marked complete. */
+function closeOpen(rows: TryRow[], close: (row: TryItemRow) => boolean): TryRow[] {
+ return rows.map((row) =>
+ row.kind === "item" && row.open && close(row) ? { ...row, open: false } : row,
+ );
+}
+
+/**
+ * The rendered view's rows with one more payload: an item's event lands on that item's open row
+ * (or opens one), anything else is a row of its own. Rows keep their places.
+ */
+export function addPayload(rows: readonly TryRow[], payload: string): TryRow[] {
+ const id = rows.length;
+ const ev = parseEvent(payload);
+ if (ev === null) {
+ return [
+ ...rows,
+ { kind: "event", id, type: "?", fields: [{ value: cut(payload), quiet: true }] },
+ ];
+ }
+ const dot = ev.type.lastIndexOf(".");
+ const item = ev.type.slice(0, dot);
+ const phase = ev.type.slice(dot + 1);
+ if (ITEMS.has(item) && (phase === "delta" || phase === "done")) {
+ const key = itemKey(ev, item);
+ const at = rows.findLastIndex((r) => r.kind === "item" && r.open && r.key === key);
+ const prev = at >= 0 ? (rows[at] as TryItemRow) : undefined;
+ const row = itemRow(prev, id, ev, item, phase === "done");
+ return at >= 0 ? rows.map((r, i) => (i === at ? row : r)) : [...rows, row];
+ }
+ const origin = originOf(ev);
+ let kept = [...rows];
+ // A streamed summary has no `.done`: its compaction's end is what completes it.
+ if (ev.type === "compaction.done") {
+ kept = closeOpen(kept, (r) => r.item === "summary" && r.origin === origin);
+ }
+ // Nothing of a run is still coming after its end.
+ if (ev.type === "run.done") kept = closeOpen(kept, () => true);
+ return [
+ ...kept,
+ {
+ kind: "event",
+ id,
+ type: ev.type,
+ fields: eventFields(ev),
+ ...(origin !== undefined ? { origin } : {}),
+ ...(ev.type === "approval.requested"
+ ? { approval: { toolCallId: ev.tool_call.tool_call_id, pending: true } }
+ : {}),
+ },
+ ];
+}
+
+/** Milliseconds from `run.started` to `run.done`, by the server's clock; null when unreadable. */
+export function elapsedMs(started: string, done: string): number | null {
+ const ms = Date.parse(done) - Date.parse(started);
+ return Number.isFinite(ms) && ms >= 0 ? ms : null;
+}
+
+/** The two views of a run: its rows with fragments merged, or its payloads as received. */
+export type TryView = "rendered" | "raw";
+
+export interface TryState {
+ input: string;
+ running: boolean;
+ /** The Session the last run named: the next run continues it. */
+ sessionId: string | null;
+ /** The current run's `run.started` time; null until it arrives, so Stop knows whom to ask. */
+ startedAt: string | null;
+ /** The current run's payloads, exactly as received. */
+ payloads: string[];
+ /** The rendered view's rows. */
+ rows: TryRow[];
+ view: TryView;
+ /** The run's outcome, once `run.done` arrived. */
+ result: { run: RunResult; elapsedMs: number | null } | null;
+ /** A refusal before the stream. */
+ error: { status: number; code: string; message: string } | null;
+ /** The body ended before `run.done`. */
+ broken: boolean;
+ /** `[DONE]` arrived. */
+ closed: boolean;
+}
+
+export type TryAction =
+ | { type: "input"; text: string }
+ | { type: "start" }
+ | { type: "payload"; data: string }
+ | { type: "httpError"; status: number; code: string; message: string }
+ /** The body closed; `stopped` when it was this panel that closed it (Stop before run.started, leaving). */
+ | { type: "ended"; stopped?: boolean }
+ | { type: "view"; view: TryView }
+ | { type: "decided"; toolCallId: string }
+ | { type: "reset" };
+
+/** The panel before its first run: the example in the input, no Session. */
+export function initialTryState(input: string): TryState {
+ return {
+ input,
+ running: false,
+ sessionId: null,
+ startedAt: null,
+ payloads: [],
+ rows: [],
+ view: "rendered",
+ result: null,
+ error: null,
+ broken: false,
+ closed: false,
+ };
+}
+
+/** The rows with the approval of `toolCallId` (or, without one, every approval) no longer open. */
+function settle(rows: TryRow[], toolCallId?: string): TryRow[] {
+ return rows.map((r) =>
+ r.kind === "event" &&
+ r.approval?.pending === true &&
+ (toolCallId === undefined || r.approval.toolCallId === toolCallId)
+ ? { ...r, approval: { ...r.approval, pending: false } }
+ : r,
+ );
+}
+
+/** What the run comes to, folded from every payload it sent; null when the stream never said. */
+function resultOf(payloads: readonly string[], doneAt: string, startedAt: string | null) {
+ const collector = new RunCollector();
+ for (const payload of payloads) {
+ const ev = parseEvent(payload);
+ if (ev !== null) collector.add(ev);
+ }
+ try {
+ return {
+ run: collector.result(),
+ elapsedMs: startedAt === null ? null : elapsedMs(startedAt, doneAt),
+ };
+ } catch {
+ return null;
+ }
+}
+
+export function reduceTry(state: TryState, action: TryAction): TryState {
+ switch (action.type) {
+ case "input":
+ return { ...state, input: action.text };
+ case "start":
+ return {
+ ...state,
+ running: true,
+ startedAt: null,
+ payloads: [],
+ rows: [],
+ result: null,
+ error: null,
+ broken: false,
+ closed: false,
+ };
+ case "payload": {
+ if (action.data === "[DONE]") return { ...state, closed: true };
+ const payloads = [...state.payloads, action.data];
+ const rows = addPayload(state.rows, action.data);
+ const ev = parseEvent(action.data);
+ if (ev?.type === "run.started") {
+ return { ...state, payloads, rows, sessionId: ev.session_id, startedAt: ev.at };
+ }
+ if (ev?.type === "approval.decided") {
+ return { ...state, payloads, rows: settle(rows, ev.tool_call_id) };
+ }
+ if (ev?.type === "run.done") {
+ // Finished: the input clears for a follow-up on the same Session.
+ return {
+ ...state,
+ payloads,
+ rows: settle(rows),
+ result: resultOf(payloads, ev.at, state.startedAt),
+ input: "",
+ };
+ }
+ return { ...state, payloads, rows };
+ }
+ case "httpError":
+ return {
+ ...state,
+ running: false,
+ error: { status: action.status, code: action.code, message: action.message },
+ };
+ case "ended":
+ return {
+ ...state,
+ running: false,
+ rows: settle(closeOpen(state.rows, () => true)),
+ broken: action.stopped !== true && state.result === null && state.error === null,
+ };
+ case "view":
+ return { ...state, view: action.view };
+ case "decided":
+ return { ...state, rows: settle(state.rows, action.toolCallId) };
+ case "reset":
+ return { ...initialTryState(state.input), view: state.view };
+ }
+}
+
+/** The request the next run sends: the input, and the Session to continue once there is one. */
+export function tryBody(state: TryState): RunRequest {
+ return {
+ input: state.input,
+ ...(state.sessionId !== null ? { session_id: state.sessionId } : {}),
+ };
+}
+
+/** The `data:` lines as received, `[DONE]` last once it came: what the raw view prints. */
+export function rawLines(state: Pick<TryState, "payloads" | "closed">): string[] {
+ const lines = state.payloads.map((payload) => `data: ${payload}`);
+ return state.closed ? [...lines, "data: [DONE]"] : lines;
+}
+
+/** The Agent a run goes to. */
+export interface TryTarget {
+ projectId: string;
+ agentId: string;
+}
+
+/**
+ * One run: the request through the try route, then one `payload` per event of the body as it
+ * arrives, then `ended`. A refusal before the stream is `httpError`; aborting `signal` (Stop
+ * before run.started, or leaving the tab) ends it as stopped.
+ */
+export async function runTry(
+ target: TryTarget,
+ dispatch: (action: TryAction) => void,
+ body: RunRequest,
+ signal: AbortSignal,
+): Promise<void> {
+ dispatch({ type: "start" });
+ try {
+ const res = await api.tryAgentApi(target.projectId, target.agentId, body, { signal });
+ if (res.body !== null) {
+ for await (const data of readSse(res.body)) dispatch({ type: "payload", data });
+ }
+ dispatch({ type: "ended" });
+ } catch (err) {
+ if (signal.aborted) dispatch({ type: "ended", stopped: true });
+ else if (err instanceof ApiError) {
+ dispatch({ type: "httpError", status: err.status, code: err.code, message: err.message });
+ } else dispatch({ type: "ended" });
+ }
+}
+
+/**
+ * Stop: once the run has named its Session, the Session's abort route — the stream stays open
+ * and ends with `run.done` aborted, as a program sees it; before that, the request itself is
+ * aborted.
+ */
+export async function stopTry(state: TryState, controller: AbortController | null): Promise<void> {
+ if (state.startedAt !== null && state.sessionId !== null) {
+ await api.postAbort(state.sessionId);
+ return;
+ }
+ controller?.abort();
+}
+
+/**
+ * An inline answer to an approval the run asked for, through the Session's approvals route; its
+ * buttons go at once, and the stream's `approval.decided` says how it was decided.
+ */
+export async function answerApproval(
+ sessionId: string,
+ toolCallId: string,
+ decision: "allow" | "deny",
+ dispatch: (action: TryAction) => void,
+): Promise<void> {
+ await api.postApproval(sessionId, toolCallId, { decision });
+ dispatch({ type: "decided", toolCallId });
+}
diff --git a/packages/web/src/features/agents/api-try-panel.tsx b/packages/web/src/features/agents/api-try-panel.tsx
new file mode 100644
index 00000000..bb0c8bda
--- /dev/null
+++ b/packages/web/src/features/agents/api-try-panel.tsx
@@ -0,0 +1,543 @@
+/**
+ * The API tab's Try it section, for the Project owner: one framed block holding the question and
+ * Run, and under them the output. Run sends one real API run through the try route — the owner's
+ * sign-in in place of a key, the runs route's handler behind it — and the output shows its stream
+ * as a program would receive it.
+ *
+ * The output is one box in two views, switched in its header beside the Session the run named:
+ * Rendered, one numbered row per item or event — an item's fragments merged into the content
+ * they add up to, the answer included — and Raw, one numbered line per `data:` payload exactly
+ * as received, scrolling sideways rather than wrapping. Both views share the box's height and
+ * scroll inside it. The strip under them names the run's outcome: the status, the Request count,
+ * the output and total tokens, the cache-read and cache-write tokens when there are any, and the
+ * elapsed time; or, in the danger tone, why there is none.
+ *
+ * Running again continues the same Session, as a program does with `session_id`; New
+ * conversation starts over. Stop asks the Session's abort route, so the stream still ends with
+ * its `run.done`; an approval the Agent's API approval mode asks for is answered on its row.
+ * Leaving the tab mid-run closes the connection, which aborts the run on the server.
+ *
+ * `ApiTryView` is the section for one state, with no state of its own; the reducer and the
+ * driver behind `ApiTryPanel` live in api-try-log.ts.
+ */
+import { useEffect, useLayoutEffect, useReducer, useRef } from "react";
+import type { KeyboardEvent, ReactNode } from "react";
+import {
+ ApprovalButtons,
+ Button,
+ Card,
+ CopyButton,
+ Input,
+ Segmented,
+ StreamingCaret,
+ Text,
+ toastError,
+} from "@lmliheng/penguin-ui";
+import { apiErrorText } from "../../lib/api-error";
+import { formatBytes } from "../../lib/format";
+import { S } from "../../lib/strings";
+import { toneInk } from "../../lib/tone";
+import {
+ answerApproval,
+ initialTryState,
+ rawLines,
+ reduceTry,
+ rowLabel,
+ runTry,
+ stopTry,
+ tryBody,
+} from "./api-try-log";
+import type { TryEventRow, TryField, TryItemRow, TryRow, TryState, TryView } from "./api-try-log";
+
+export interface ApiTryViewProps {
+ input: string;
+ running: boolean;
+ sessionId: string | null;
+ /** The rendered view's rows. */
+ rows: TryRow[];
+ /** The raw view's lines: every payload as received, `[DONE]` last once it came. */
+ lines: string[];
+ view: TryView;
+ result: TryState["result"];
+ error: TryState["error"];
+ /** The body ended before `run.done`. */
+ broken: boolean;
+ /** Nothing can run (the admin has the Agent API off); `disabledReason` says why. */
+ disabled: boolean;
+ disabledReason?: string;
+ onInput: (text: string) => void;
+ onRun: () => void;
+ onStop: () => void;
+ onNewSession: () => void;
+ onView: (view: TryView) => void;
+ /** Answers an approval; its buttons stay disabled until the answer settles. */
+ onApprove: (toolCallId: string, decision: "allow" | "deny") => Promise<void>;
+}
+
+/** One labelled value of the outcome strip: the label muted, the value bold. */
+function Stat({
+ label,
+ children,
+ mono = false,
+}: {
+ label: string;
+ children: string;
+ mono?: boolean;
+}) {
+ return (
+ <span>
+ <span className="text-fg-muted">{label}</span>{" "}
+ <span className={`font-semibold tabular-nums ${mono ? "font-mono" : ""}`}>{children}</span>
+ </span>
+ );
+}
+
+/**
+ * The output's scroll box, one for both views, so switching keeps the box where it is; each view
+ * opens at its top. While the reader is at the end it stays there as the content grows — rows
+ * arriving, a row filling in, text re-wrapping once a font lands — and a reader who scrolled up
+ * to read is left where they are.
+ */
+function OutputBody({ view, children }: { view: TryView; children: ReactNode }) {
+ const box = useRef<HTMLDivElement>(null);
+ const content = useRef<HTMLDivElement>(null);
+ const atEnd = useRef(true);
+ /** Where the box last scrolled itself: only a reader going above it leaves the end. */
+ const placed = useRef(0);
+ const shownView = useRef(view);
+ useLayoutEffect(() => {
+ const el = box.current;
+ if (shownView.current === view || el === null) return;
+ shownView.current = view;
+ el.scrollTop = 0;
+ placed.current = 0;
+ atEnd.current = el.scrollHeight <= el.clientHeight;
+ }, [view]);
+ useEffect(() => {
+ const el = box.current;
+ const inner = content.current;
+ if (el === null || inner === null || typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver(() => {
+ if (!atEnd.current) return;
+ el.scrollTop = el.scrollHeight;
+ placed.current = el.scrollTop;
+ });
+ observer.observe(inner);
+ return () => observer.disconnect();
+ }, []);
+ return (
+ <div
+ ref={box}
+ data-testid="api-try-output"
+ onScroll={(e) => {
+ const el = e.currentTarget;
+ // The box's own scroll can land after more rows came in, short of the new end: that is
+ // not the reader leaving it. Going back up is.
+ if (el.scrollHeight - el.scrollTop - el.clientHeight < 16) atEnd.current = true;
+ else if (el.scrollTop < placed.current - 1) atEnd.current = false;
+ }}
+ className="max-h-[32rem] overflow-auto border-t border-[color:inherit] bg-canvas"
+ >
+ <div ref={content}>{children}</div>
+ </div>
+ );
+}
+
+/**
+ * The line number in front of a row or a raw line, in the code gutter's ink. It stays put while
+ * a raw line scrolls sideways, and a selection never picks it up.
+ */
+const GUTTER =
+ "sticky left-0 min-w-[3ch] select-none bg-canvas pl-3 pr-3 text-right font-mono text-xs leading-5 tabular-nums text-[var(--ui-code-gutter)]";
+
+/** A tool call's arguments, indented when they parse; as received while they do not yet. */
+function prettyArguments(text: string): string {
+ if (text.trim() === "") return "";
+ try {
+ return JSON.stringify(JSON.parse(text), null, 2);
+ } catch {
+ return text;
+ }
+}
+
+/**
+ * Name/value pairs as one run of text: the names muted, the values bold. Inline, so a long value
+ * (a list of tool names, an error message) carries on after the short ones and wraps as prose.
+ */
+function fieldLine(fields: readonly TryField[], after?: ReactNode) {
+ return (
+ <p className="break-words font-mono text-xs leading-5">
+ {fields.map((field, i) => (
+ <span key={i} className="mr-3">
+ {field.name !== undefined && <span className="text-fg-muted">{field.name} </span>}
+ <span className={field.quiet === true ? "text-fg-muted" : "font-semibold text-fg"}>
+ {field.value}
+ </span>
+ </span>
+ ))}
+ {after}
+ </p>
+ );
+}
+
+/** A merged item's content: prose in the text face, arguments and output in mono. */
+function itemContent(row: TryItemRow, live: boolean) {
+ const caret = live && row.open ? <StreamingCaret /> : null;
+ const tags =
+ row.tags.length > 0 ? (
+ <span className="mr-2 font-mono text-xs text-fg-muted">{row.tags.join(" ")}</span>
+ ) : null;
+ switch (row.item) {
+ case "text":
+ case "thinking":
+ case "summary":
+ return (
+ <p
+ className={`whitespace-pre-wrap break-words text-sm leading-relaxed ${
+ row.item === "text" ? "text-fg" : "text-fg-muted"
+ }`}
+ >
+ {tags}
+ {row.text}
+ {caret}
+ </p>
+ );
+ case "tool_call": {
+ const args = prettyArguments(row.text);
+ return (
+ <div className="font-mono text-xs leading-5">
+ <p className="break-words">
+ {tags}
+ <span className="font-semibold text-fg">{row.name}</span>
+ {args === "" && caret}
+ </p>
+ {args !== "" && (
+ <pre className="whitespace-pre-wrap break-words text-fg-muted">
+ {args}
+ {caret}
+ </pre>
+ )}
+ </div>
+ );
+ }
+ case "tool_result":
+ return (
+ <div className="font-mono text-xs leading-5">
+ {(tags !== null || row.images !== undefined) && (
+ <p>
+ {tags}
+ {row.images !== undefined && (
+ <span className="text-fg-muted">
+ images <span className="font-semibold text-fg">{row.images}</span>
+ </span>
+ )}
+ </p>
+ )}
+ {/* The output's closing newline would read as an empty line. */}
+ <pre className="whitespace-pre-wrap break-words">
+ {row.text.replace(/\n+$/, "")}
+ {caret}
+ </pre>
+ </div>
+ );
+ default:
+ // Inline media and image inputs: what they are and how big, never the bytes.
+ return fieldLine(
+ [
+ ...row.tags.map((tag) => ({ value: tag, quiet: true })),
+ ...(row.media !== undefined
+ ? [{ value: row.media.mime }, { value: formatBytes(row.media.bytes) }]
+ : [{ value: row.text }]),
+ ],
+ caret,
+ );
+ }
+}
+
+/**
+ * A standalone event's content: its key fields, and under them, while an approval waits, the
+ * conversation view's own Allow and Deny.
+ */
+function eventContent(row: TryEventRow, onApprove: ApiTryViewProps["onApprove"]) {
+ const approval = row.approval;
+ return (
+ <>
+ {fieldLine(row.fields)}
+ {approval?.pending === true && (
+ <div className="mt-2">
+ <ApprovalButtons
+ labels={{ allow: S.chat.approve, deny: S.chat.deny }}
+ onDecide={(decision) => onApprove(approval.toolCallId, decision)}
+ />
+ </div>
+ )}
+ </>
+ );
+}
+
+/** The rendered view: one numbered row per item or event, the label before the content. */
+function renderedRows(p: ApiTryViewProps) {
+ return (
+ <ol className="grid grid-cols-[auto_minmax(0,1fr)] gap-y-2 py-3 pr-3 sm:grid-cols-[auto_auto_minmax(0,1fr)]">
+ {p.rows.map((row, i) => (
+ <li
+ key={row.id}
+ data-testid="api-try-row"
+ className="col-span-2 grid grid-cols-subgrid items-baseline sm:col-span-3"
+ >
+ <span aria-hidden className={GUTTER}>
+ {i + 1}
+ </span>
+ <span
+ className="font-mono text-xs leading-5 text-fg-muted sm:pr-4"
+ data-tooltip={row.origin}
+ >
+ {row.origin !== undefined && "↳ "}
+ {rowLabel(row)}
+ </span>
+ <div className="col-start-2 min-w-0 sm:col-start-auto">
+ {row.kind === "item" ? itemContent(row, p.running) : eventContent(row, p.onApprove)}
+ </div>
+ </li>
+ ))}
+ </ol>
+ );
+}
+
+/** The raw view: one numbered line per payload as received, scrolling sideways, never wrapping. */
+function rawRows(lines: readonly string[]) {
+ return (
+ <ol className="grid w-max min-w-full grid-cols-[auto_1fr] py-3 pr-3">
+ {lines.map((line, i) => (
+ <li key={i} data-testid="api-try-raw-line" className="col-span-2 grid grid-cols-subgrid">
+ <span aria-hidden className={GUTTER}>
+ {i + 1}
+ </span>
+ <span className="whitespace-pre font-mono text-xs leading-5">{line}</span>
+ </li>
+ ))}
+ </ol>
+ );
+}
+
+/** The section as it reads for one state of a run: no state of its own. */
+export function ApiTryView(p: ApiTryViewProps) {
+ const canRun = !p.disabled && !p.running && p.input.trim() !== "";
+ const onKey = (e: KeyboardEvent<HTMLInputElement>) => {
+ // An IME's Enter commits its composition; it does not run.
+ if (e.key === "Enter" && !e.nativeEvent.isComposing && canRun) p.onRun();
+ };
+ const run = p.result?.run;
+ const shown = p.view === "rendered" ? p.rows.length : p.lines.length;
+ // Nothing has run yet, or the last run was stopped before it said anything.
+ const idle = !p.running && p.rows.length === 0 && p.error === null && !p.broken;
+ const notice =
+ p.error !== null
+ ? `${p.error.status} ${p.error.code} — ${p.error.message}`
+ : p.broken
+ ? S.agent.apiTryStreamBroken
+ : null;
+
+ return (
+ // A flush card, the page's box whose bands run edge to edge: the theme draws its frame as it
+ // draws the examples' code blocks above.
+ <Card as="section" padding="none">
+ {/* The question: what a run does, the input and Run. */}
+ <div className="space-y-3 bg-canvas p-4">
+ <h2>
+ <Text variant="eyebrow" as="span">
+ {S.agent.apiTry}
+ </Text>
+ </h2>
+ <p className="text-xs text-fg-muted">{S.agent.apiTryHint}</p>
+ <div className="flex items-start gap-2">
+ <div className="min-w-0 flex-1">
+ <Input
+ size="sm"
+ aria-label={S.agent.apiTry}
+ value={p.input}
+ placeholder={p.sessionId !== null ? S.agent.apiTryFollowUp : S.agent.apiTryExample}
+ disabled={p.disabled || p.running}
+ onChange={(e) => p.onInput(e.target.value)}
+ onKeyDown={onKey}
+ />
+ </div>
+ {p.running ? (
+ <Button size="sm" variant="ghost" className="shrink-0" onClick={p.onStop}>
+ {S.agent.apiTryStop}
+ </Button>
+ ) : (
+ <Button
+ size="sm"
+ variant="primary"
+ className="shrink-0"
+ disabled={!canRun}
+ data-tooltip={p.disabledReason}
+ onClick={p.onRun}
+ >
+ {S.agent.apiTryRun}
+ </Button>
+ )}
+ </div>
+ </div>
+
+ {/* The output's header: the Session on the left, the views on the right. One line from sm
+ up, so neither a view switch nor a long id pushes the switch down — a narrow box cuts the
+ id short, which is whole in its copy button and on the run.started row; below sm the
+ Session and the switch take a line each. */}
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2 border-t border-[color:inherit] bg-[var(--ui-code-bg)] px-3 py-1.5 sm:flex-nowrap">
+ {p.sessionId !== null && (
+ <div className="flex min-w-0 items-center gap-x-2">
+ <span className="shrink-0 font-mono text-xs text-fg-muted">session_id</span>
+ <span className="min-w-0 truncate font-mono text-xs font-semibold">{p.sessionId}</span>
+ <CopyButton
+ text={p.sessionId}
+ label={S.agent.apiCopy("session_id")}
+ size="sm"
+ className="shrink-0"
+ />
+ <Button
+ size="xs"
+ variant="ghost"
+ className="shrink-0"
+ disabled={p.running}
+ onClick={p.onNewSession}
+ >
+ {S.agent.apiTryNewSession}
+ </Button>
+ </div>
+ )}
+ <div className="ml-auto flex shrink-0 items-center gap-2">
+ {/* In both views, so switching never moves the switch. */}
+ {p.lines.length > 0 && (
+ <CopyButton
+ text={p.lines.join("\n")}
+ label={S.agent.apiTryCopyRaw}
+ size="sm"
+ className="shrink-0"
+ />
+ )}
+ <div className="w-32">
+ <Segmented
+ cols={2}
+ options={[
+ { value: "rendered", label: S.agent.apiTryRendered },
+ { value: "raw", label: S.agent.apiTryRaw },
+ ]}
+ value={p.view}
+ onChange={p.onView}
+ />
+ </div>
+ </div>
+ </div>
+
+ {(shown > 0 || p.running || idle) && (
+ <OutputBody view={p.view}>
+ {shown > 0 ? (
+ p.view === "rendered" ? (
+ renderedRows(p)
+ ) : (
+ rawRows(p.lines)
+ )
+ ) : p.running ? (
+ // The request is out; nothing has come back yet.
+ <p className="px-4 py-3 text-sm">
+ <StreamingCaret />
+ </p>
+ ) : (
+ <p className="px-4 py-6 text-center text-xs text-fg-muted">{S.agent.apiTryEmpty}</p>
+ )}
+ </OutputBody>
+ )}
+
+ {/* The outcome: what run.done reported, or why the stream gave none. */}
+ {(run !== undefined || notice !== null) && (
+ <div
+ data-slot="foot"
+ className="flex flex-wrap items-baseline gap-x-3 gap-y-1 border-t border-[color:inherit] bg-[var(--ui-code-bg)] px-3 py-1.5 text-xs"
+ >
+ {notice !== null ? (
+ <p className={toneInk.danger}>{notice}</p>
+ ) : (
+ run !== undefined && (
+ <>
+ <Stat label={S.agent.apiTryStatus} mono>
+ {run.status}
+ </Stat>
+ <Stat label={S.agent.apiTryRequests}>{String(run.requests)}</Stat>
+ <Stat
+ label={S.agent.apiTryTokens}
+ >{`${run.usage.output} / ${run.usage.total}`}</Stat>
+ {run.usage.cache_read > 0 && (
+ <Stat label={S.agent.apiTryCacheRead}>{String(run.usage.cache_read)}</Stat>
+ )}
+ {run.usage.cache_write > 0 && (
+ <Stat label={S.agent.apiTryCacheWrite}>{String(run.usage.cache_write)}</Stat>
+ )}
+ {p.result !== null && p.result.elapsedMs !== null && (
+ <Stat
+ label={S.agent.apiTryElapsed}
+ >{`${(p.result.elapsedMs / 1000).toFixed(1)} s`}</Stat>
+ )}
+ </>
+ )
+ )}
+ </div>
+ )}
+ </Card>
+ );
+}
+
+/** The section with its run: the state, the connection to close on leaving, the handlers. */
+export function ApiTryPanel({
+ projectId,
+ agentId,
+ disabledReason,
+}: {
+ projectId: string;
+ agentId: string;
+ /** Set when nothing can run, saying why (the admin has the Agent API off). */
+ disabledReason?: string;
+}) {
+ const [state, dispatch] = useReducer(reduceTry, S.agent.apiTryExample, initialTryState);
+ const connection = useRef<AbortController | null>(null);
+ // Leaving mid-run closes the connection, and the server aborts the run.
+ useEffect(() => () => connection.current?.abort(), []);
+ const disabled = disabledReason !== undefined;
+
+ return (
+ <ApiTryView
+ input={state.input}
+ running={state.running}
+ sessionId={state.sessionId}
+ rows={state.rows}
+ lines={rawLines(state)}
+ view={state.view}
+ result={state.result}
+ error={state.error}
+ broken={state.broken}
+ disabled={disabled}
+ disabledReason={disabledReason}
+ onInput={(text) => dispatch({ type: "input", text })}
+ onRun={() => {
+ if (state.running || disabled || state.input.trim() === "") return;
+ const controller = new AbortController();
+ connection.current = controller;
+ void runTry({ projectId, agentId }, dispatch, tryBody(state), controller.signal);
+ }}
+ onStop={() => {
+ stopTry(state, connection.current).catch((e: unknown) => toastError(apiErrorText(e)));
+ }}
+ onNewSession={() => dispatch({ type: "reset" })}
+ onView={(view) => dispatch({ type: "view", view })}
+ onApprove={async (toolCallId, decision) => {
+ if (state.sessionId === null) return;
+ try {
+ await answerApproval(state.sessionId, toolCallId, decision, dispatch);
+ } catch (e) {
+ toastError(apiErrorText(e));
+ }
+ }}
+ />
+ );
+}
diff --git a/packages/web/src/features/settings/agent-api-section.tsx b/packages/web/src/features/settings/agent-api-section.tsx
new file mode 100644
index 00000000..2f4cc91d
--- /dev/null
+++ b/packages/web/src/features/settings/agent-api-section.tsx
@@ -0,0 +1,135 @@
+/**
+ * Settings › Server › Agent API (admin only): "Allow the Agent API", the server-wide switch over
+ * every Agent's public API (`agentApiEnabled` in /api/admin/settings, on by default). Off, every
+ * request to the API is refused; each Agent's own switch, approval mode and keys are kept.
+ *
+ * The switch applies on the flip, like Chrome extension connections'. Turning it on writes at
+ * once. Turning it off asks first, in the danger tone — every program calling an Agent fails from
+ * then on — and the knob stays on until the answer is yes. A write that fails puts the knob back
+ * on the stored value and says why under it.
+ */
+import { useEffect, useState } from "react";
+import type { ServerSettingsResponse } from "@lmliheng/penguin-server/api";
+import { ConfirmModal, SettingsSection, ToggleRow, toastError } from "@lmliheng/penguin-ui";
+import * as api from "../../api/endpoints";
+import { apiErrorText } from "../../lib/api-error";
+import { S } from "../../lib/strings";
+import { toneInk } from "../../lib/tone";
+
+/** Turns the switch off on the server. Reached only through the confirm. */
+const switchOffAgentApiServer = (): Promise<ServerSettingsResponse> =>
+ api.adminPutSettings({ agentApiEnabled: false });
+
+/**
+ * The question before the switch goes off: the danger tone and what follows. Answered yes, it
+ * says the write began, writes the switch off, and hands the outcome on: the stored value, or
+ * the failure.
+ */
+export function AgentApiServerOffConfirm({
+ open,
+ onClose,
+ onWriting,
+ onSettled,
+}: {
+ open: boolean;
+ onClose: () => void;
+ onWriting: () => void;
+ onSettled: (outcome: { enabled: boolean } | { error: unknown }) => void;
+}) {
+ return (
+ <ConfirmModal
+ open={open}
+ title={S.settings.agentApiOffTitle}
+ onClose={onClose}
+ onConfirm={() => {
+ onClose();
+ onWriting();
+ switchOffAgentApiServer().then(
+ (res) => onSettled({ enabled: res.settings.agentApiEnabled }),
+ (error: unknown) => onSettled({ error }),
+ );
+ }}
+ confirmLabel={S.settings.agentApiOff}
+ cancelLabel={S.common.cancel}
+ >
+ <p className="text-sm text-fg-muted">{S.settings.agentApiOffConfirm}</p>
+ </ConfirmModal>
+ );
+}
+
+export function AgentApiSection() {
+ /** The last value the server confirmed; null until the settings load. */
+ const [stored, setStored] = useState<boolean | null>(null);
+ /** What the switch shows: the stored value, or the pending one while a write is in flight. */
+ const [enabled, setEnabled] = useState(true);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | undefined>(undefined);
+ const [confirmOff, setConfirmOff] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ void api
+ .adminGetSettings()
+ .then((res) => {
+ if (cancelled) return;
+ setStored(res.settings.agentApiEnabled);
+ setEnabled(res.settings.agentApiEnabled);
+ })
+ .catch((e: unknown) => {
+ if (!cancelled) toastError(apiErrorText(e));
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ /** Where a write landed: the stored value, or back to the last one with the reason. */
+ const settle = (outcome: { enabled: boolean } | { error: unknown }, previous: boolean) => {
+ if ("enabled" in outcome) {
+ setStored(outcome.enabled);
+ setEnabled(outcome.enabled);
+ } else {
+ setEnabled(previous);
+ setError(apiErrorText(outcome.error));
+ }
+ setBusy(false);
+ };
+
+ const turnOn = () => {
+ if (stored === null || busy) return;
+ setEnabled(true);
+ setError(undefined);
+ setBusy(true);
+ api.adminPutSettings({ agentApiEnabled: true }).then(
+ (res) => settle({ enabled: res.settings.agentApiEnabled }, stored),
+ (err: unknown) => settle({ error: err }, stored),
+ );
+ };
+
+ return (
+ <SettingsSection>
+ <div>
+ <ToggleRow
+ label={S.settings.agentApiToggle}
+ checked={enabled}
+ onChange={(next) => {
+ if (next) turnOn();
+ else setConfirmOff(true);
+ }}
+ disabled={stored === null || busy}
+ />
+ {error !== undefined && <p className={`mt-2 text-xs ${toneInk.danger}`}>{error}</p>}
+ </div>
+ <AgentApiServerOffConfirm
+ open={confirmOff}
+ onClose={() => setConfirmOff(false)}
+ onWriting={() => {
+ setEnabled(false);
+ setError(undefined);
+ setBusy(true);
+ }}
+ onSettled={(outcome) => settle(outcome, stored ?? true)}
+ />
+ </SettingsSection>
+ );
+}
diff --git a/packages/web/src/features/settings/settings-dialog.tsx b/packages/web/src/features/settings/settings-dialog.tsx
index a7aaf98b..bf934150 100644
--- a/packages/web/src/features/settings/settings-dialog.tsx
+++ b/packages/web/src/features/settings/settings-dialog.tsx
@@ -27,6 +27,7 @@ import { AccountSection } from "./account-section";
import { ProxySection } from "./proxy-section";
import { UploadsSection } from "./uploads-section";
import { CompanySection } from "./company-section";
+import { AgentApiSection } from "./agent-api-section";
import { PluginsSection } from "./plugins-section";
import { StorageSection } from "./storage-section";
import { AdminUsersSection } from "../admin/admin-users-page";
@@ -55,6 +56,8 @@ const SECTION_ICONS: Record<SettingsSectionKey, string> = {
uploads: "M12 15V4m0 0L7 9m5-5l5 5M4 20h16",
/** The building the mode switch wears: company mode. */
company: ICONS.building,
+ /** Angle brackets: programs calling the Agents. */
+ agentApi: ICONS.angleBrackets,
/** A drive: the data root's storage ledger. */
storage: ICONS.hardDrive,
/** Puzzle piece: plugins. */
@@ -109,6 +112,7 @@ export function SettingsDialog({
proxy: S.settings.proxyTitle,
uploads: S.settings.uploadLimitsTitle,
company: S.settings.companyModeTitle,
+ agentApi: S.settings.agentApiTitle,
plugins: S.settings.pluginsTitle,
storage: S.settings.storageTitle,
users: S.admin.users,
@@ -124,6 +128,7 @@ export function SettingsDialog({
proxy: S.settings.proxyInfo,
uploads: S.settings.uploadLimitsInfo(uploadLimits.attachmentMaxCount, uploadLimits.imageMaxMb),
company: S.settings.companyModeServerInfo,
+ agentApi: S.settings.agentApiHint,
plugins: S.settings.pluginsInfo,
storage: S.settings.storageInfo,
};
@@ -170,6 +175,7 @@ export function SettingsDialog({
{current === "proxy" && <ProxySection />}
{current === "uploads" && <UploadsSection />}
{current === "company" && <CompanySection />}
+ {current === "agentApi" && <AgentApiSection />}
{current === "plugins" && (
<PluginsSection {...(pluginFocus !== undefined ? { focus: pluginFocus } : {})} />
)}
diff --git a/packages/web/src/lib/session-activity.ts b/packages/web/src/lib/session-activity.ts
index 66ee4e0e..5012bf12 100644
--- a/packages/web/src/lib/session-activity.ts
+++ b/packages/web/src/lib/session-activity.ts
@@ -68,7 +68,7 @@ export function sessionBackgroundTasks(session: Pick<SessionInfo, "backgroundTas
/** The subset of a row this function needs (a whole SessionInfo satisfies it). */
export type SessionActivityRow = Pick<
SessionInfo,
- "sessionId" | "status" | "hasTrace" | "lastActiveAt"
+ "sessionId" | "status" | "hasTrace" | "lastActiveAt" | "source"
>;
/**
@@ -76,6 +76,10 @@ export type SessionActivityRow = Pick<
* whether the user has looked at this Session since it last ran, and whether it is the
* conversation currently open.
*
+ * Only a person's conversation (`source` `user`, or not yet known) is ever unread. A background
+ * Session — API, scheduled, subagent or CLI — finishes without anyone waiting on it, so its row
+ * shows no "new reply" mark; it still shows when it is running.
+ *
* The open conversation is never unread: the user is looking at it. The chat page reaches the
* same conclusion by stamping the seen marker once a run settles under the user's eyes, but it
* does so in an effect, one tick after the run-end event moved the row's `lastActiveAt` —
@@ -87,6 +91,7 @@ export function sessionRowActivity(
activeSessionId: string | null,
): SessionActivity {
const unread =
+ (session.source === undefined || session.source === "user") &&
session.sessionId !== activeSessionId &&
isSessionUnread(seen, session.sessionId, session.lastActiveAt);
return sessionActivity(session.status, session.hasTrace, unread);
diff --git a/packages/web/src/lib/settings-sections.ts b/packages/web/src/lib/settings-sections.ts
index 149fc60d..1dd04030 100644
--- a/packages/web/src/lib/settings-sections.ts
+++ b/packages/web/src/lib/settings-sections.ts
@@ -35,6 +35,7 @@ export type SettingsSectionKey =
| "proxy"
| "uploads"
| "company"
+ | "agentApi"
| "plugins"
| "storage"
| "users";
@@ -76,6 +77,8 @@ const SECTION_RULES: ReadonlyArray<SettingsSection & { visible(viewer: SettingsV
{ key: "uploads", group: "server", visible: (v) => v.isAdmin },
// The company-mode master switch: server-global like the proxy and upload limits.
{ key: "company", group: "server", visible: (v) => v.isAdmin },
+ // Whether any Agent's public API answers at all: server-global, like company mode.
+ { key: "agentApi", group: "server", visible: (v) => v.isAdmin },
// The sandbox, and the options loaded plugins declare (server-global, like the plugins themselves).
{ key: "plugins", group: "server", visible: (v) => v.isAdmin },
// The data root's storage ledger: a server-global report an admin reads. Read-only, so unlike
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 78dc4073..ee26da3b 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -376,6 +376,14 @@ export const en: Strings = {
creditsLicense: "License",
creditsSource: "Source",
creditsLicenseText: "Full license text",
+ agentApiTitle: "Agent API",
+ agentApiToggle: "Allow the Agent API",
+ agentApiHint:
+ "Off refuses every agent's API requests; per-agent switches, approval modes and keys are kept.",
+ agentApiOffTitle: "Turn the Agent API off?",
+ agentApiOffConfirm:
+ "Every agent's API on this server refuses requests at once, and the programs calling them fail until it is on again. Per-agent switches, approval modes and keys are kept.",
+ agentApiOff: "Turn off",
/** Rail headings: the viewer's own preferences vs. the whole server's. */
groupPersonal: "Personal",
groupServer: "Server",
@@ -1467,6 +1475,7 @@ export const en: Strings = {
tabHooks: "Hooks",
tabVault: "Vault",
tabSchedules: "Schedules",
+ tabApi: "API",
stateDir: "State path",
copyStateDir: "Copy State path",
agentsMd: "AGENTS.md",
@@ -1664,6 +1673,64 @@ export const en: Strings = {
: `Kernel updated to ${version}; every tab was already current or kept as customized`,
kernelUpdateKeptIntro: "Kept whole because customized:",
kernelListSeparator: ", ",
+ apiEnable: "Enable API access",
+ apiEnableHint:
+ "External programs can talk to this agent with the URL, a key and the Agent ID; the conversations appear in the sidebar's Background folder.",
+ apiOwnerOnly: "Only the Project owner can change these settings.",
+ apiAdminOff:
+ "An admin has turned the Agent API off for this server: every API request is refused, and the settings and keys here are kept.",
+ apiApprovalMode: "Approval mode for API conversations",
+ apiApprovalModeHint:
+ "Applies to API conversations created from now on; when a mode asks, the request goes to the caller and can also be answered here.",
+ apiConnection: "Connection",
+ apiBaseUrl: "Base URL",
+ apiAgentId: "Agent ID",
+ apiCopy: (what: string): string => `Copy ${what}`,
+ apiKeys: "Keys",
+ apiKeysEmpty: "No keys yet.",
+ apiNewKey: "New key",
+ apiKeyName: "Key name",
+ apiKeyCreated: "Created",
+ apiKeyLastUsed: "Last used",
+ apiKeyNever: "never",
+ apiKeyShownOnce: "This key is shown once; copy it now.",
+ apiCopySecret: "Copy key",
+ apiKeyDone: "Done",
+ apiDeleteKey: "Delete key",
+ apiDeleteKeyBody: (name: string): string =>
+ `Delete the key "${name}"? Programs using it are refused at once; this cannot be undone.`,
+ apiOpen: "Allow keyless access",
+ apiOpenHint:
+ "Anything that can reach this address can talk to the agent; recommended for loopback use only.",
+ apiExamples: "Examples",
+ apiOpenTitle: "Allow keyless access?",
+ apiOpenBody:
+ "Once on, anything that can reach this server's address can talk to this agent without a key, on the Project's models and credentials, with tools run under the API conversations' approval mode. Turn it on only for a server that listens on loopback.",
+ apiOpenConfirm: "Allow anyway",
+ apiOffTitle: "Turn API access off?",
+ apiOffBody:
+ "External programs can no longer talk to this agent. The approval mode and the keys are kept and work again once it is back on.",
+ apiOff: "Turn off",
+ apiOn: "API access on",
+ apiTry: "Try it",
+ apiTryHint:
+ "Runs the route a program calls, your sign-in in place of a key, and shows what it receives; filed under Background.",
+ apiTryExample: "What time is it now?",
+ apiTryRun: "Run",
+ apiTryStop: "Stop",
+ apiTryFollowUp: "Continue this conversation…",
+ apiTryNewSession: "New conversation",
+ apiTryRendered: "Rendered",
+ apiTryRaw: "Raw",
+ apiTryCopyRaw: "Copy the raw lines",
+ apiTryEmpty: "The stream shows here once you run.",
+ apiTryStatus: "Status",
+ apiTryRequests: "Requests",
+ apiTryTokens: "Tokens (output / total)",
+ apiTryCacheRead: "Cache read",
+ apiTryCacheWrite: "Cache write",
+ apiTryElapsed: "Elapsed",
+ apiTryStreamBroken: "The stream ended before run.done.",
},
models: {
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 41b7ab64..5a7c8611 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -445,6 +445,14 @@ export const zh = {
creditsLicense: "许可",
creditsSource: "来源",
creditsLicenseText: "许可全文",
+ /** Settings › Server › Agent API: the admin's switch over every Agent's public API, and the question before it goes off. */
+ agentApiTitle: "Agent API",
+ agentApiToggle: "允许 Agent API",
+ agentApiHint: "关闭后所有 Agent 的 API 请求均被拒绝;各 Agent 的开关、审批模式与密钥保留。",
+ agentApiOffTitle: "关闭 Agent API?",
+ agentApiOffConfirm:
+ "这台服务器上所有 Agent 的 API 会立即拒绝请求,调用它们的外部程序都会失败,直到重新开启。各 Agent 的开关、审批模式与密钥保留。",
+ agentApiOff: "关闭",
/** Rail headings: the viewer's own preferences vs. the whole server's. */
groupPersonal: "个人",
groupServer: "服务器",
@@ -1515,6 +1523,7 @@ export const zh = {
tabHooks: "钩子",
tabVault: "密钥保险柜",
tabSchedules: "定时任务",
+ tabApi: "API",
stateDir: "State 路径",
copyStateDir: "复制 State 路径",
agentsMd: "AGENTS.md",
@@ -1691,6 +1700,70 @@ export const zh = {
: `内核已更新至 ${version},设置页均已是当前默认或保持自定义`,
kernelUpdateKeptIntro: "以下设置页因自定义被整体保留:",
kernelListSeparator: "、",
+ /** The API tab: this server's switch for the Agent's public API, its approval mode, keys and examples. */
+ apiEnable: "开启 API 访问",
+ apiEnableHint:
+ "外部程序可通过 URL、密钥与 Agent ID 与此 Agent 对话;对话归入侧栏的「后台会话」。",
+ apiOwnerOnly: "只有 Project 所有者可以更改这些设置。",
+ apiAdminOff:
+ "管理员已在服务器设置中关闭 Agent API:所有 API 请求都会被拒绝,这里的设置与密钥保留。",
+ apiApprovalMode: "API 会话的审批模式",
+ apiApprovalModeHint:
+ "应用于之后新建的 API 会话;需要确认时,确认请求会发给调用方,也可在 Web App 中回答。",
+ apiConnection: "连接",
+ apiBaseUrl: "Base URL",
+ apiAgentId: "Agent ID",
+ /** A copy button beside a connection value, named for what it copies. */
+ apiCopy: (what: string): string => `复制 ${what}`,
+ apiKeys: "密钥",
+ apiKeysEmpty: "还没有密钥。",
+ apiNewKey: "新建密钥",
+ apiKeyName: "密钥名称",
+ apiKeyCreated: "创建",
+ apiKeyLastUsed: "最近使用",
+ apiKeyNever: "从未",
+ apiKeyShownOnce: "此密钥只显示一次,请立即复制。",
+ apiCopySecret: "复制密钥",
+ apiKeyDone: "完成",
+ apiDeleteKey: "删除密钥",
+ apiDeleteKeyBody: (name: string): string =>
+ `删除密钥「${name}」?使用它的程序会立即被拒绝,此操作不可撤销。`,
+ apiOpen: "允许无密钥访问",
+ apiOpenHint: "任何能访问此地址的程序都能与该 Agent 对话;仅建议本机使用。",
+ apiExamples: "示例",
+ /** Turning the Agent's API off asks first: every program using it is refused from then on. */
+ apiOpenTitle: "允许无密钥访问?",
+ apiOpenBody:
+ "开启后,任何能访问此服务器地址的程序都无需密钥即可与该 Agent 对话,用的是本 Project 的模型与凭据,工具按 API 会话的审批模式执行。仅建议在只监听本机的服务器上开启。",
+ apiOpenConfirm: "仍然开启",
+ apiOffTitle: "关闭 API 访问?",
+ apiOffBody: "外部程序会立即无法与此 Agent 对话。审批模式与密钥保留,重新开启后照常可用。",
+ apiOff: "关闭",
+ /** The Agents list's plug mark on an Agent whose API is on. */
+ apiOn: "已开启 API 访问",
+ /** The tab's Try it: one real API run on the owner's sign-in, shown as a program receives it. */
+ apiTry: "试一试",
+ apiTryHint:
+ "以你的登录身份走程序用的同一条运行路由,收到的就是程序会收到的事件流;开出的会话归入侧栏的「后台会话」。",
+ apiTryExample: "现在几点了?",
+ apiTryRun: "运行",
+ apiTryStop: "停止",
+ /** The input's placeholder once a run has named its Session: the next run continues it. */
+ apiTryFollowUp: "继续这个会话…",
+ apiTryNewSession: "新会话",
+ /** The output's two views: the stream with fragments merged, and its `data:` lines as received. */
+ apiTryRendered: "渲染",
+ apiTryRaw: "原始",
+ apiTryCopyRaw: "复制原始行",
+ /** The output before the first run. */
+ apiTryEmpty: "运行后,事件流显示在这里。",
+ apiTryStatus: "状态",
+ apiTryRequests: "Request",
+ apiTryTokens: "Token(输出 / 合计)",
+ apiTryCacheRead: "缓存读",
+ apiTryCacheWrite: "缓存写",
+ apiTryElapsed: "用时",
+ apiTryStreamBroken: "事件流在 run.done 之前结束。",
},
models: {
diff --git a/packages/web/test/agent-api-tab.test.ts b/packages/web/test/agent-api-tab.test.ts
new file mode 100644
index 00000000..a070688f
--- /dev/null
+++ b/packages/web/test/agent-api-tab.test.ts
@@ -0,0 +1,379 @@
+/**
+ * An Agent's public API in the Web App: the Agent page's API tab (features/agents/api-tab.tsx),
+ * the Agents list's mark (agents-page.tsx) and the admin's server-wide switch
+ * (features/settings/agent-api-section.tsx). The views render to static markup and the
+ * confirmations are driven through their handlers against the fetch fake (node env, no DOM).
+ *
+ * - An Agent whose API is off shows the switch alone: no approval mode, no address, no keys, no
+ * examples.
+ * - Enabled, the tab shows the approval mode select on the stored mode, the Base URL and the
+ * Agent ID each with its copy button, and every key by its prefix with when it was created and
+ * last used (or that it never was).
+ * - A created key's secret is on screen in its own panel, whose copy button copies exactly the
+ * secret and whose Done hands back; with no secret pending there is no panel.
+ * - The examples call the real Base URL and Agent ID, with the key left as $ADELIE_AGENT_KEY.
+ * - With the admin's server-wide switch off, the tab's switch is disabled and says why, to every
+ * member and not only an admin (the tab's own read carries the switch); a member who is not the
+ * owner finds every control disabled, no key actions, and is told why.
+ * - Turning the API off asks first, in the danger tone. Answered yes, it writes the switch off
+ * and hands on what the server stored; a failed write is handed on as the failure.
+ * - Deleting a key asks first, naming it. Answered yes, it deletes that key and hands on its id;
+ * a refused delete says why and hands on nothing.
+ * - The Agents list carries the plug mark, named for screen readers, only on an Agent whose API
+ * is on.
+ * - Turning the Agent API off server-wide asks first, in the danger tone; answered yes, it writes
+ * the switch off and hands on what the server stored.
+ * - The owner's tab ends with Try it, its input holding the example question; a member's tab has
+ * no Try it.
+ * - With the admin's server-wide switch off, Try it's input and Run are disabled, and Run carries
+ * the reason.
+ */
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { createElement, isValidElement } from "react";
+import type { ReactElement, ReactNode } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import type {
+ AgentApiKeyInfo,
+ AgentApiResponse,
+ AgentApiSettings,
+} from "@lmliheng/penguin-server/api";
+import { Button, CopyButton, Select, ToggleRow } from "@lmliheng/penguin-ui";
+import {
+ AgentApiOffConfirm,
+ KeylessOnConfirm,
+ ApiTabView,
+ DeleteKeyConfirm,
+ OneTimeKey,
+ agentApiBaseUrl,
+ agentApiExamples,
+} from "../src/features/agents/api-tab";
+import type { ApiTabViewProps } from "../src/features/agents/api-tab";
+import { AgentApiMark } from "../src/features/agents/agents-page";
+import { AgentApiServerOffConfirm } from "../src/features/settings/agent-api-section";
+import { S } from "../src/lib/strings";
+import { apiError, json, stubFetch } from "./helpers/fetch";
+
+const toasts = vi.hoisted(() => [] as string[]);
+
+vi.mock("@lmliheng/penguin-ui", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@lmliheng/penguin-ui")>();
+ return {
+ ...actual,
+ toastSuccess: (text: string) => toasts.push(`success: ${text}`),
+ toastError: (text: string) => toasts.push(`error: ${text}`),
+ };
+});
+
+const USED: AgentApiKeyInfo = {
+ keyId: "kq3VtX9cRb2LmN0a",
+ name: "docs-site search",
+ prefix: "penguin_Zr8kQ2vT",
+ createdBy: "admin",
+ createdAt: "2026-10-01T08:00:00.000Z",
+ lastUsedAt: "2026-10-07T09:30:00.000Z",
+};
+const FRESH: AgentApiKeyInfo = {
+ ...USED,
+ keyId: "Hc7pW2sYd4EfJ6uB",
+ name: "weekly report",
+ prefix: "penguin_4mGxL7pA",
+ lastUsedAt: null,
+};
+const ON: AgentApiSettings = {
+ enabled: true,
+ open: false,
+ approvalMode: "read-only",
+ keys: [USED, FRESH],
+};
+const BASE = agentApiBaseUrl("http://127.0.0.1:7369");
+/** Obviously fake and short: no key-shaped literal lives in the tests. */
+const SECRET = "penguin_fake-secret";
+
+const noop = () => {};
+function props(over: Partial<ApiTabViewProps> = {}): ApiTabViewProps {
+ return {
+ projectId: "demo",
+ agentId: "coder",
+ settings: ON,
+ serverEnabled: true,
+ isOwner: true,
+ busy: false,
+ baseUrl: BASE,
+ agentRef: "demo/coder",
+ draftName: null,
+ secret: null,
+ onToggleEnabled: noop,
+ onApprovalMode: noop,
+ onToggleOpen: noop,
+ onStartKey: noop,
+ onDraftName: noop,
+ onCreateKey: noop,
+ onCancelKey: noop,
+ onSecretDone: noop,
+ onDeleteKey: noop,
+ ...over,
+ };
+}
+const render = (over: Partial<ApiTabViewProps> = {}) =>
+ renderToStaticMarkup(createElement(ApiTabView, props(over)));
+
+/** The props a ConfirmModal element was given. */
+type Confirm = ReactElement<{
+ open: boolean;
+ tone?: string;
+ title: string;
+ confirmLabel: string;
+ children: ReactNode;
+ onConfirm: () => void;
+}>;
+
+/** Every element of `type` in a tree of plain elements, its children followed. */
+function find(node: ReactNode, type: unknown): ReactElement<Record<string, unknown>>[] {
+ return ([] as ReactNode[])
+ .concat(node)
+ .filter(isValidElement)
+ .flatMap((el) => {
+ const element = el as ReactElement<{ children?: ReactNode }>;
+ const own = element.type === type ? [element as ReactElement<Record<string, unknown>>] : [];
+ return [...own, ...find(element.props.children, type)];
+ });
+}
+
+beforeEach(() => {
+ toasts.length = 0;
+});
+
+describe("the API tab", () => {
+ it("shows the switch alone while the API is off", () => {
+ const html = render({ settings: { ...ON, enabled: false } });
+ expect(html).toContain(`aria-label="${S.agent.apiEnable}"`);
+ expect(html).not.toContain(S.agent.apiApprovalMode);
+ expect(html).not.toContain(BASE);
+ expect(html).not.toContain(USED.prefix);
+ expect(html).not.toContain("ADELIE_AGENT_KEY");
+ });
+
+ it("shows the approval mode, the address with copy buttons and every key by its prefix once on", () => {
+ const html = render();
+ expect(html).toContain(S.agent.apiApprovalMode);
+ expect(html).toContain(S.chat.approvalModeNames["read-only"]);
+ expect(html).toContain(BASE);
+ expect(html).toContain(`aria-label="${S.agent.apiCopy(S.agent.apiBaseUrl)}"`);
+ expect(html).toContain("demo/coder");
+ expect(html).toContain(`aria-label="${S.agent.apiCopy(S.agent.apiAgentId)}"`);
+ expect(html.split('data-testid="api-key"').length - 1).toBe(2);
+ expect(html).toContain(`${USED.prefix}…`);
+ expect(html).toContain(`${FRESH.prefix}…`);
+ expect(html).toContain(S.agent.apiKeyNever);
+ });
+
+ it("puts a created key's secret in its own panel, whose copy button copies exactly it", () => {
+ expect(render({ secret: SECRET })).toContain(SECRET);
+ expect(find(ApiTabView(props()), OneTimeKey)).toEqual([]);
+
+ const onDone = vi.fn();
+ const panel = OneTimeKey({ secret: SECRET, onDone });
+ const [copy] = find(panel, CopyButton);
+ expect(copy!.props.text).toBe(SECRET);
+ const [done] = find(panel, Button);
+ (done!.props.onClick as () => void)();
+ expect(onDone).toHaveBeenCalledOnce();
+ });
+
+ it("calls the real Base URL and Agent ID in its examples, the key left to the environment", () => {
+ const { curl, sdk } = agentApiExamples(BASE, "demo/coder");
+ expect(curl).toContain(`curl -N ${BASE}/agents/demo/coder/runs`);
+ expect(curl).toContain("Bearer $ADELIE_AGENT_KEY");
+ expect(sdk).toContain(`baseUrl: "${BASE}"`);
+ expect(sdk).toContain(`agent: "demo/coder"`);
+ expect(sdk).toContain("process.env.ADELIE_AGENT_KEY");
+ expect(render()).toContain(`${BASE}/agents/demo/coder/runs`);
+ });
+
+ it("disables the switch and tells any member why when the admin has the API off server-wide", () => {
+ const [toggle] = find(ApiTabView(props({ serverEnabled: false })), ToggleRow);
+ expect(toggle!.props.disabled).toBe(true);
+ expect(render({ serverEnabled: false })).toContain(S.agent.apiAdminOff);
+ expect(render({ serverEnabled: false, isOwner: false })).toContain(S.agent.apiAdminOff);
+ expect(render()).not.toContain(S.agent.apiAdminOff);
+ });
+
+ it("ends the owner's tab with Try it, its input holding the example; a member's tab has none", () => {
+ const html = render();
+ expect(html.indexOf(S.agent.apiTry)).toBeGreaterThan(html.indexOf(S.agent.apiExamples));
+ expect(html).toContain(`value="${S.agent.apiTryExample}"`);
+ expect(render({ isOwner: false })).not.toContain(S.agent.apiTry);
+ expect(render({ settings: { ...ON, enabled: false } })).not.toContain(S.agent.apiTry);
+ });
+
+ it("disables Try it's input and Run when the admin has the API off, Run saying why", () => {
+ const html = render({ serverEnabled: false });
+ const section = html.slice(html.indexOf(S.agent.apiTry));
+ expect(section).toMatch(/<input[^>]*disabled=""/);
+ // The section's first button is Run.
+ const run = /<button[^>]*>[^<]*<\/button>/.exec(section)?.[0] ?? "";
+ expect(run).toContain(S.agent.apiTryRun);
+ expect(run).toContain('disabled=""');
+ expect(run).toContain(`data-tooltip="${S.agent.apiAdminOff}"`);
+ const enabled = render().slice(render().indexOf(S.agent.apiTry));
+ expect(enabled).not.toMatch(/<input[^>]*disabled=""/);
+ });
+
+ it("leaves a member who is not the owner every control disabled and no key action", () => {
+ const tree = ApiTabView(props({ isOwner: false }));
+ const toggles = find(tree, ToggleRow);
+ expect(toggles).toHaveLength(2);
+ expect(toggles.every((t) => t.props.disabled === true)).toBe(true);
+ expect(find(tree, Select)[0]!.props.disabled).toBe(true);
+ const html = render({ isOwner: false });
+ expect(html).toContain(S.agent.apiOwnerOnly);
+ expect(html).not.toContain(S.agent.apiNewKey);
+ expect(html).not.toContain(`aria-label="${S.agent.apiDeleteKey} ${USED.name}"`);
+ expect(render()).toContain(`aria-label="${S.agent.apiDeleteKey} ${USED.name}"`);
+ });
+});
+
+describe("turning an Agent's API off", () => {
+ const confirm = (onSettled: (o: unknown) => void, onWriting = noop) =>
+ AgentApiOffConfirm({
+ open: true,
+ projectId: "demo",
+ agentId: "coder",
+ onClose: noop,
+ onWriting,
+ onSettled,
+ }) as Confirm;
+
+ it("asks first in the danger tone; answered yes, writes it off and hands on what was stored", async () => {
+ const stored: AgentApiResponse = { api: { ...ON, enabled: false }, serverEnabled: true };
+ const fetch = stubFetch(() => json(stored));
+ const onWriting = vi.fn();
+ const onSettled = vi.fn();
+ const question = confirm(onSettled, onWriting);
+ expect(question.props.tone).toBeUndefined();
+ expect(question.props.title).toBe(S.agent.apiOffTitle);
+ expect(fetch.requests).toEqual([]);
+ question.props.onConfirm();
+ expect(onWriting).toHaveBeenCalledOnce();
+ await vi.waitFor(() => expect(onSettled).toHaveBeenCalledExactlyOnceWith(stored));
+ expect(fetch.requests.map((r) => [r.method, r.path, r.body])).toEqual([
+ ["PUT", "/api/projects/demo/agents/coder/api", { enabled: false }],
+ ]);
+ });
+
+ it("hands on a failed write as the failure", async () => {
+ stubFetch(() => apiError(403, "forbidden"));
+ const onSettled = vi.fn();
+ confirm(onSettled).props.onConfirm();
+ await vi.waitFor(() => expect(onSettled).toHaveBeenCalledOnce());
+ expect(onSettled.mock.calls[0]![0]).toHaveProperty("error");
+ });
+});
+
+describe("allowing keyless access", () => {
+ const confirm = (onSettled: (o: unknown) => void, onWriting = noop) =>
+ KeylessOnConfirm({
+ open: true,
+ projectId: "demo",
+ agentId: "coder",
+ onClose: noop,
+ onWriting,
+ onSettled,
+ }) as Confirm;
+
+ it("warns first in the danger tone; answered yes, writes it on and hands on what was stored", async () => {
+ const stored: AgentApiResponse = { api: { ...ON, open: true }, serverEnabled: true };
+ const fetch = stubFetch(() => json(stored));
+ const onWriting = vi.fn();
+ const onSettled = vi.fn();
+ const question = confirm(onSettled, onWriting);
+ expect(question.props.tone).toBeUndefined();
+ expect(question.props.title).toBe(S.agent.apiOpenTitle);
+ expect(fetch.requests).toEqual([]);
+ question.props.onConfirm();
+ expect(onWriting).toHaveBeenCalledOnce();
+ await vi.waitFor(() => expect(onSettled).toHaveBeenCalledExactlyOnceWith(stored));
+ expect(fetch.requests.map((r) => [r.method, r.path, r.body])).toEqual([
+ ["PUT", "/api/projects/demo/agents/coder/api", { open: true }],
+ ]);
+ });
+
+ it("hands on a failed write as the failure", async () => {
+ stubFetch(() => apiError(403, "forbidden"));
+ const onSettled = vi.fn();
+ confirm(onSettled).props.onConfirm();
+ await vi.waitFor(() => expect(onSettled).toHaveBeenCalledOnce());
+ expect(onSettled.mock.calls[0]![0]).toHaveProperty("error");
+ });
+});
+
+describe("deleting a key", () => {
+ it("asks first, naming the key; answered yes, deletes it and hands on its id", async () => {
+ const fetch = stubFetch(() => new Response(null, { status: 204 }));
+ const onDeleted = vi.fn();
+ const question = DeleteKeyConfirm({
+ record: USED,
+ projectId: "demo",
+ agentId: "coder",
+ onClose: noop,
+ onDeleted,
+ }) as Confirm;
+ expect(question.props.open).toBe(true);
+ expect(question.props.tone).toBeUndefined();
+ expect(renderToStaticMarkup(question.props.children as ReactElement)).toContain(
+ S.agent.apiDeleteKeyBody(USED.name),
+ );
+ expect(fetch.requests).toEqual([]);
+ question.props.onConfirm();
+ await vi.waitFor(() => expect(onDeleted).toHaveBeenCalledExactlyOnceWith(USED.keyId));
+ expect(fetch.requests.map((r) => `${r.method} ${r.path}`)).toEqual([
+ `DELETE /api/projects/demo/agents/coder/api/keys/${USED.keyId}`,
+ ]);
+ });
+
+ it("says why a refused delete failed, and hands on nothing", async () => {
+ stubFetch(() => apiError(404, "key_not_found", "No such key."));
+ const onDeleted = vi.fn();
+ (
+ DeleteKeyConfirm({
+ record: USED,
+ projectId: "demo",
+ agentId: "coder",
+ onClose: noop,
+ onDeleted,
+ }) as Confirm
+ ).props.onConfirm();
+ await vi.waitFor(() => expect(toasts).toHaveLength(1));
+ expect(toasts[0]).toMatch(/^error: /);
+ expect(onDeleted).not.toHaveBeenCalled();
+ });
+});
+
+describe("the Agents list", () => {
+ it("marks an Agent whose API is on with the plug, named for screen readers, and no other", () => {
+ const on = renderToStaticMarkup(createElement(AgentApiMark, { enabled: true }));
+ expect(on).toContain(`data-tooltip="${S.agent.apiOn}"`);
+ expect(on).toContain(`<span class="sr-only">${S.agent.apiOn}</span>`);
+ expect(renderToStaticMarkup(createElement(AgentApiMark, { enabled: false }))).toBe("");
+ });
+});
+
+describe("the server-wide switch", () => {
+ it("asks first in the danger tone; answered yes, writes it off and hands on what was stored", async () => {
+ const fetch = stubFetch(() => json({ settings: { agentApiEnabled: false } }));
+ const onSettled = vi.fn();
+ const question = AgentApiServerOffConfirm({
+ open: true,
+ onClose: noop,
+ onWriting: noop,
+ onSettled,
+ }) as Confirm;
+ expect(question.props.tone).toBeUndefined();
+ expect(fetch.requests).toEqual([]);
+ question.props.onConfirm();
+ await vi.waitFor(() => expect(onSettled).toHaveBeenCalledExactlyOnceWith({ enabled: false }));
+ expect(fetch.requests.map((r) => [r.method, r.path, r.body])).toEqual([
+ ["PUT", "/api/admin/settings", { agentApiEnabled: false }],
+ ]);
+ });
+});
diff --git a/packages/web/test/agent-handoff.test.ts b/packages/web/test/agent-handoff.test.ts
index d83e80a4..d31dd848 100644
--- a/packages/web/test/agent-handoff.test.ts
+++ b/packages/web/test/agent-handoff.test.ts
@@ -28,6 +28,7 @@ const agent = (agentId: string, name?: string): AgentSummary => ({
skillCount: 0,
hookCount: 0,
memoryCount: 0,
+ apiEnabled: false,
});
const AGENTS: AgentSummary[] = [
diff --git a/packages/web/test/api-try-log.test.ts b/packages/web/test/api-try-log.test.ts
new file mode 100644
index 00000000..26479da1
--- /dev/null
+++ b/packages/web/test/api-try-log.test.ts
@@ -0,0 +1,942 @@
+/**
+ * The API tab's Try it (features/agents/api-try-log.ts and api-try-panel.tsx): a run sent
+ * through the try route and read back as the AMSP stream a program receives. The driver runs
+ * against the package's fetch fake, which serves scripted SSE bodies — whole, or held open and
+ * fed as the server would (the abort and approvals routes feed the rest); the view renders to
+ * static markup and its controls are driven through their handlers (node env, no DOM).
+ *
+ * The rendered view's rows:
+ * - An item's fragments are one row showing them joined while the item streams; fragments of
+ * another tool call or another Session start a row of their own.
+ * - Once the item's .done arrives the row shows the .done's content in place of the joined
+ * fragments, whatever the fragments said.
+ * - Tool results that interleave stay on their own rows, found by their tool call.
+ * - A streamed summary, which has no .done, is its fragments joined; its compaction's end
+ * completes it.
+ * - Rows are numbered in the order they first appear, and a merged row keeps its number when
+ * its .done arrives after later rows.
+ * - A payload that is not an AMSP event is a row of its own; every other event is one row
+ * naming its key fields (tools.ready its tool count and names, not their JSON).
+ *
+ * The panel:
+ * - A run against the fake reads as numbered rows — the answer as its text row, the call's
+ * arguments indented — with the Session id; the input clears to the follow-up placeholder,
+ * and the next run carries that session_id.
+ * - A row still streaming carries the live caret while the run lasts; a complete one does not.
+ * Arguments that do not parse yet show as received.
+ * - Inline media shows its type and size, never its bytes; fragments of one add up.
+ * - A row says what sets its item apart: a text the harness sent, a call cut short, a result's
+ * images; a child Session's rows carry the chain they came from.
+ * - The outcome strip shows the cache-read and cache-write token counts, each only when it is
+ * not zero.
+ * - The raw view prints one numbered line per payload exactly as received, [DONE] last, and its
+ * copy button copies exactly those lines.
+ * - A refusal before the stream shows its status, code and message in the outcome strip and no
+ * rows; a body that ends before run.done keeps its rows and says the stream broke.
+ * - Stop once the run has named its Session posts the Session's abort, and the stream's own
+ * run.done aborted is shown; Stop before run.started aborts the request, says nothing went
+ * wrong, and leaves the box as it was before any run.
+ * - An approval.requested row offers Allow and Deny; an answer posts the decision to the
+ * Session's approvals route and its buttons go; an approval.decided from elsewhere, or the
+ * run's end, clears them too.
+ * - New conversation forgets the Session and the output and keeps the input.
+ */
+import { describe, expect, it, vi } from "vitest";
+import { createElement, isValidElement } from "react";
+import type { ReactElement, ReactNode } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import type { AmspEvent, TokenCounts } from "@lmliheng/amsp";
+import { ApprovalButtons, Button, CopyButton } from "@lmliheng/penguin-ui";
+import {
+ addPayload,
+ answerApproval,
+ eventFields,
+ initialTryState,
+ rawLines,
+ reduceTry,
+ runTry,
+ stopTry,
+ tryBody,
+} from "../src/features/agents/api-try-log";
+import type { TryAction, TryRow, TryState } from "../src/features/agents/api-try-log";
+import { ApiTryView } from "../src/features/agents/api-try-panel";
+import type { ApiTryViewProps } from "../src/features/agents/api-try-panel";
+import { S } from "../src/lib/strings";
+import { apiError, stubFetch } from "./helpers/fetch";
+
+const SESSION = "session-2026-10-09-09-30-00-7d2e41c8";
+const TARGET = { projectId: "demo", agentId: "coder" };
+const TRY_PATH = "/api/projects/demo/agents/coder/api/try";
+const T0 = Date.parse("2026-10-09T09:30:00.000Z");
+const at = (ms: number) => new Date(T0 + ms).toISOString();
+const usage = (output: number, total: number): TokenCounts => ({
+ cache_read: 900,
+ cache_write: 120,
+ output,
+ total,
+});
+
+const STARTED: AmspEvent = {
+ type: "run.started",
+ at: at(0),
+ session_id: SESSION,
+ agent: "demo/coder",
+};
+const text = (t: string, origin?: string[]): AmspEvent => ({
+ type: "text.delta",
+ at: at(0),
+ role: "assistant",
+ text: t,
+ ...(origin ? { origin } : {}),
+});
+const callFragment = (id: string, name: string, args: string): AmspEvent => ({
+ type: "tool_call.delta",
+ at: at(0),
+ tool_call_id: id,
+ name,
+ arguments: args,
+});
+const output = (id: string, out: string): AmspEvent => ({
+ type: "tool_result.delta",
+ at: at(0),
+ tool_call_id: id,
+ output: out,
+});
+
+/**
+ * The example run as the server streams it: the model runs `date` and answers, over two
+ * Requests, fragments first; the tool's result ends after its Request does.
+ */
+const TIME_RUN: AmspEvent[] = [
+ STARTED,
+ {
+ type: "tools.ready",
+ at: at(10),
+ tools: [
+ { name: "exec_command", description: "Run a command." },
+ { name: "read_file", description: "Read a file." },
+ ],
+ },
+ { type: "request.started", at: at(20), request: 1 },
+ { ...callFragment("call_1", "exec_command", '{"cmd": '), at: at(500) },
+ { ...callFragment("call_1", "", '"date"}'), at: at(510) },
+ {
+ type: "tool_call.done",
+ at: at(520),
+ tool_call_id: "call_1",
+ name: "exec_command",
+ arguments: '{"cmd":"date"}',
+ stop_reason: "completed",
+ },
+ { ...output("call_1", ""), at: at(530) },
+ { type: "request.done", at: at(540), request: 1, status: "completed", usage: usage(31, 1376) },
+ {
+ type: "tool_result.done",
+ at: at(700),
+ tool_call_id: "call_1",
+ output: "Fri Oct 9 09:30:00 UTC 2026\n",
+ stop_reason: "completed",
+ },
+ { type: "request.started", at: at(720), request: 2 },
+ { ...text("It is "), at: at(1500) },
+ { ...text("09:30 UTC."), at: at(1510) },
+ {
+ type: "text.done",
+ at: at(1520),
+ role: "assistant",
+ text: "It is 09:30 UTC.",
+ stop_reason: "completed",
+ },
+ { type: "request.done", at: at(1530), request: 2, status: "completed", usage: usage(55, 1352) },
+ {
+ type: "run.done",
+ at: at(3200),
+ status: "completed",
+ requests: 2,
+ usage: usage(86, 2728),
+ session_usage: usage(86, 2728),
+ },
+];
+const RUN_DONE = TIME_RUN.at(-1) as Extract<AmspEvent, { type: "run.done" }>;
+
+const encoder = new TextEncoder();
+const block = (data: string) => `data: ${data}\n\n`;
+const payloadOf = (e: AmspEvent | "[DONE]") => (e === "[DONE]" ? e : JSON.stringify(e));
+
+/** A whole SSE body, as the try route sends it. */
+function sse(events: Array<AmspEvent | "[DONE]">): Response {
+ return new Response(events.map((e) => block(payloadOf(e))).join(""), {
+ status: 200,
+ headers: { "content-type": "text/event-stream; charset=utf-8" },
+ });
+}
+
+/** A body held open: the test (or another route of the fake) sends the rest and closes it. */
+function live(signal: AbortSignal | null) {
+ let stream!: ReadableStreamDefaultController<Uint8Array>;
+ const body = new ReadableStream<Uint8Array>({ start: (c) => void (stream = c) });
+ // Like a real fetch: aborting the request errors its body.
+ signal?.addEventListener("abort", () => {
+ try {
+ stream.error(signal.reason);
+ } catch {
+ // Already closed.
+ }
+ });
+ return {
+ response: new Response(body, {
+ status: 200,
+ headers: { "content-type": "text/event-stream; charset=utf-8" },
+ }),
+ send(...events: Array<AmspEvent | "[DONE]">) {
+ for (const e of events) stream.enqueue(encoder.encode(block(payloadOf(e))));
+ },
+ close() {
+ stream.close();
+ },
+ };
+}
+
+/** The panel's state, driven by the reducer the panel uses. */
+function harness(state: TryState = initialTryState(S.agent.apiTryExample)) {
+ const h = {
+ state,
+ dispatch: (action: TryAction) => {
+ h.state = reduceTry(h.state, action);
+ },
+ };
+ return h;
+}
+
+/** A run under way: started, and these events received. */
+function streaming(events: AmspEvent[]): TryState {
+ const h = harness();
+ h.dispatch({ type: "start" });
+ for (const e of events) h.dispatch({ type: "payload", data: JSON.stringify(e) });
+ return h.state;
+}
+
+const noop = () => {};
+function viewProps(state: TryState, over: Partial<ApiTryViewProps> = {}): ApiTryViewProps {
+ return {
+ input: state.input,
+ running: state.running,
+ sessionId: state.sessionId,
+ rows: state.rows,
+ lines: rawLines(state),
+ view: state.view,
+ result: state.result,
+ error: state.error,
+ broken: state.broken,
+ disabled: false,
+ onInput: noop,
+ onRun: noop,
+ onStop: noop,
+ onNewSession: noop,
+ onView: noop,
+ onApprove: async () => {},
+ ...over,
+ };
+}
+const html = (state: TryState, over: Partial<ApiTryViewProps> = {}) =>
+ renderToStaticMarkup(createElement(ApiTryView, viewProps(state, over)));
+
+const ENTITIES: Record<string, string> = {
+ "&quot;": '"',
+ "&#x27;": "'",
+ "&amp;": "&",
+ "&lt;": "<",
+ "&gt;": ">",
+};
+const decode = (markup: string) =>
+ markup.replace(/&(?:quot|#x27|amp|lt|gt);/g, (e) => ENTITIES[e]!);
+/** The inner markup of every element tagged `testid`, entities decoded. */
+const tagged = (markup: string, testid: string) =>
+ [...markup.matchAll(new RegExp(`<li data-testid="${testid}"[^>]*>([\\s\\S]*?)</li>`, "g"))].map(
+ (m) => decode(m[1]!),
+ );
+const words = (inner: string) =>
+ inner
+ .replace(/<[^>]+>/g, " ")
+ .replace(/\s+/g, " ")
+ .trim();
+/** The rendered view's rows as a reader sees them: the number, the label, the content. */
+const rowsShown = (state: TryState, over: Partial<ApiTryViewProps> = {}) =>
+ tagged(html(state, over), "api-try-row").map(words);
+/** The raw view's lines as a reader sees them: the number, then the line, spaces kept. */
+const rawShown = (state: TryState) =>
+ tagged(html(state, { view: "raw" }), "api-try-raw-line").map((inner) =>
+ inner
+ .split(/<[^>]+>/)
+ .filter((cell) => cell !== "")
+ .join(" "),
+ );
+
+/** Every element of `type` in a tree of plain elements, its children followed. */
+function find(node: ReactNode, type: unknown): ReactElement<Record<string, unknown>>[] {
+ return ([] as ReactNode[])
+ .concat(node)
+ .filter(isValidElement)
+ .flatMap((el) => {
+ const element = el as ReactElement<{ children?: ReactNode }>;
+ const own = element.type === type ? [element as ReactElement<Record<string, unknown>>] : [];
+ return [...own, ...find(element.props.children, type)];
+ });
+}
+const buttonsNamed = (state: TryState, name: string, over: Partial<ApiTryViewProps> = {}) =>
+ find(ApiTryView(viewProps(state, over)), Button).filter((b) => b.props.children === name);
+/** The Allow / Deny pairs on screen, each answering through `onDecide`. */
+const approvalsOn = (state: TryState, over: Partial<ApiTryViewProps> = {}) =>
+ find(ApiTryView(viewProps(state, over)), ApprovalButtons).map(
+ (b) => b.props.onDecide as (decision: "allow" | "deny") => Promise<void>,
+ );
+
+/** The rows after these events, each sent as its payload. */
+const rowsOf = (events: AmspEvent[]): TryRow[] =>
+ events.reduce<TryRow[]>((rows, e) => addPayload(rows, JSON.stringify(e)), []);
+
+describe("the rendered view's rows", () => {
+ it("merges an item's fragments into one row that shows them joined while it streams", () => {
+ const rows = rowsOf([
+ text("Hel"),
+ text("lo wo"),
+ text("rld"),
+ callFragment("call_1", "exec_command", '{"cmd":'),
+ callFragment("call_1", "", '"ls"}'),
+ callFragment("call_2", "read_file", "{}"),
+ text("child", ["sub-1"]),
+ ]);
+ expect(rows).toMatchObject([
+ { kind: "item", item: "text", text: "Hello world", open: true },
+ { kind: "item", item: "tool_call", name: "exec_command", text: '{"cmd":"ls"}', open: true },
+ { kind: "item", item: "tool_call", name: "read_file", text: "{}", open: true },
+ { kind: "item", item: "text", text: "child", origin: "sub-1", open: true },
+ ]);
+ });
+
+ it("shows the .done's content in place of the joined fragments once it arrives", () => {
+ const rows = rowsOf([
+ text("It's "),
+ text("9:30"),
+ {
+ type: "text.done",
+ at: at(0),
+ role: "assistant",
+ text: "It is 09:30 UTC.",
+ stop_reason: "completed",
+ },
+ callFragment("call_1", "exec_command", '{"cmd": "date"'),
+ {
+ type: "tool_call.done",
+ at: at(0),
+ tool_call_id: "call_1",
+ name: "exec_command",
+ arguments: '{"cmd":"date"}',
+ stop_reason: "completed",
+ },
+ ]);
+ expect(rows).toMatchObject([
+ { item: "text", text: "It is 09:30 UTC.", open: false },
+ { item: "tool_call", text: '{"cmd":"date"}', open: false },
+ ]);
+ // A .done with no fragments before it is a row of its own, complete from the start.
+ expect(rowsOf([TIME_RUN[12]!])).toMatchObject([{ item: "text", open: false }]);
+ });
+
+ it("keeps interleaved tool results apart, each on the row of its tool call", () => {
+ const rows = rowsOf([
+ output("call_1", "a"),
+ output("call_2", "x"),
+ output("call_1", "b"),
+ {
+ type: "tool_result.done",
+ at: at(0),
+ tool_call_id: "call_2",
+ output: "xy",
+ stop_reason: "completed",
+ },
+ output("call_1", "c"),
+ ]);
+ expect(rows).toMatchObject([
+ { id: 0, item: "tool_result", text: "abc", open: true },
+ { id: 1, item: "tool_result", text: "xy", open: false },
+ ]);
+ });
+
+ it("joins a summary that has no .done, which its compaction's end completes", () => {
+ const summary = (t: string): AmspEvent => ({ type: "summary.delta", at: at(0), text: t });
+ const rows = rowsOf([
+ {
+ type: "compaction.started",
+ at: at(0),
+ reason: "context",
+ mode: "summarize",
+ context: 180000,
+ turns: 12,
+ },
+ summary("The user asked "),
+ summary("for the time."),
+ ]);
+ expect(rows.at(-1)).toMatchObject({ item: "summary", text: "The user asked for the time." });
+ expect(rows.at(-1)).toMatchObject({ open: true });
+ const ended = addPayload(
+ rows,
+ JSON.stringify({
+ type: "compaction.done",
+ at: at(0),
+ reason: "context",
+ mode: "summarize",
+ status: "completed",
+ usage: null,
+ }),
+ );
+ expect(ended.map((r) => (r.kind === "item" ? r.item : r.type))).toEqual([
+ "compaction.started",
+ "summary",
+ "compaction.done",
+ ]);
+ expect(ended[1]).toMatchObject({ text: "The user asked for the time.", open: false });
+ });
+
+ it("numbers rows in the order they first appear, a merged row keeping its number", () => {
+ const state = streaming(TIME_RUN);
+ expect(rowsShown(state).map((row) => row.split(" ").slice(0, 2).join(" "))).toEqual([
+ "1 run.started",
+ "2 tools.ready",
+ "3 request.started",
+ "4 tool_call",
+ // Its .done came after Request 1 ended; the row stays where its first fragment put it.
+ "5 tool_result",
+ "6 request.done",
+ "7 request.started",
+ "8 text",
+ "9 request.done",
+ "10 run.done",
+ ]);
+ });
+
+ it("keeps a payload that is not an AMSP event as a row of its own", () => {
+ expect(addPayload([], "not json")).toMatchObject([
+ { kind: "event", type: "?", fields: [{ value: "not json" }] },
+ ]);
+ });
+
+ it.each<[string, AmspEvent, string[], string[]]>([
+ ["run.started", STARTED, [SESSION], []],
+ [
+ "context.opened",
+ {
+ type: "context.opened",
+ at: at(0),
+ session_id: SESSION,
+ provider: "anthropic",
+ model_id: "claude-sonnet-5",
+ context_window: 200000,
+ },
+ ["anthropic/claude-sonnet-5", "200000"],
+ [],
+ ],
+ ["tools.ready", TIME_RUN[1]!, ["2", "exec_command, read_file"], ["Run a command.", "{"]],
+ [
+ "mcp_connect.started",
+ { type: "mcp_connect.started", at: at(0), servers: ["github", "linear"] },
+ ["github, linear"],
+ [],
+ ],
+ [
+ "mcp_connect.done",
+ {
+ type: "mcp_connect.done",
+ at: at(0),
+ status: "fatal",
+ results: [
+ { server: "github", transport: "http", status: "completed", duration_ms: 80, tools: 12 },
+ { server: "linear", transport: "stdio", status: "fatal", duration_ms: 5 },
+ ],
+ error: { code: "mcp_connect_failed", message: "linear did not start." },
+ },
+ ["fatal", "github completed", "linear fatal", "mcp_connect_failed", "linear did not start."],
+ [],
+ ],
+ [
+ "compaction.done",
+ {
+ type: "compaction.done",
+ at: at(0),
+ reason: "turns",
+ mode: "discard",
+ status: "completed",
+ usage: usage(40, 900),
+ },
+ ["turns", "mode discard", "completed", "output 40", "total 900"],
+ [],
+ ],
+ ["request.started", { type: "request.started", at: at(0), request: 2 }, ["#2"], []],
+ [
+ "request.done with usage",
+ { type: "request.done", at: at(0), request: 1, status: "completed", usage: usage(5, 77) },
+ ["#1", "completed", "output 5", "total 77"],
+ [],
+ ],
+ [
+ "a failed request.done to be retried",
+ {
+ type: "request.done",
+ at: at(0),
+ request: 1,
+ status: "retryable",
+ usage: null,
+ error: { code: "rate_limited", message: "Slow down." },
+ attempt: 1,
+ retry_in_ms: 2000,
+ },
+ ["retryable", "rate_limited", "Slow down.", "attempt 1", "retry_in_ms 2000"],
+ ["total"],
+ ],
+ [
+ "approval.requested",
+ {
+ type: "approval.requested",
+ at: at(0),
+ tool_call: { tool_call_id: "call_1", name: "exec_command", arguments: '{"cmd":"rm x"}' },
+ },
+ ["exec_command", '{"cmd":"rm x"}'],
+ [],
+ ],
+ [
+ "approval.decided",
+ { type: "approval.decided", at: at(0), tool_call_id: "call_1", decision: "deny" },
+ ["deny"],
+ [],
+ ],
+ [
+ "compaction.started",
+ {
+ type: "compaction.started",
+ at: at(0),
+ reason: "context",
+ mode: "summarize",
+ context: 300,
+ turns: 1,
+ },
+ ["context", "mode summarize"],
+ [],
+ ],
+ [
+ "hook.fired",
+ {
+ type: "hook.fired",
+ at: at(0),
+ hook: "pre_tool_use",
+ name: "guard",
+ decision: "deny",
+ reason: "No deletes.",
+ },
+ ["pre_tool_use", "guard", "decision deny", "No deletes."],
+ [],
+ ],
+ [
+ "run.done with an error",
+ {
+ type: "run.done",
+ at: at(0),
+ status: "aborted",
+ error: { code: "user_abort", message: "Aborted." },
+ requests: 2,
+ usage: usage(9, 314),
+ session_usage: null,
+ },
+ ["aborted", "requests 2", "output 9", "total 314", "user_abort"],
+ [],
+ ],
+ [
+ "an event this panel does not know",
+ { type: "plan.updated", at: at(0), steps: 3 } as unknown as AmspEvent,
+ ['"steps":3'],
+ ["plan.updated", at(0)],
+ ],
+ ])("the row of %s names its key fields", (_name, event, shows, hides) => {
+ const line = eventFields(event)
+ .map((f) => (f.name !== undefined ? `${f.name} ${f.value}` : f.value))
+ .join(" · ");
+ for (const s of shows) expect(line).toContain(s);
+ for (const s of hides) expect(line).not.toContain(s);
+ });
+});
+
+describe("a Try run", () => {
+ it("reads as numbered rows with the answer and the indented arguments; the next run continues the Session", async () => {
+ const fetch = stubFetch(() => sse([...TIME_RUN, "[DONE]"]));
+ const h = harness();
+ await runTry(TARGET, h.dispatch, tryBody(h.state), new AbortController().signal);
+
+ expect(fetch.requests.map((r) => [r.method, r.path, r.body])).toEqual([
+ ["POST", TRY_PATH, { input: S.agent.apiTryExample }],
+ ]);
+ expect(h.state).toMatchObject({ running: false, sessionId: SESSION, broken: false });
+ const rows = rowsShown(h.state);
+ expect(rows[7]).toBe("8 text It is 09:30 UTC.");
+ expect(rows[4]).toBe("5 tool_result Fri Oct 9 09:30:00 UTC 2026");
+ const [call] = tagged(html(h.state), "api-try-row").filter((r) => r.includes("tool_call"));
+ expect(call).toContain('{\n "cmd": "date"\n}');
+ const view = html(h.state);
+ expect(view).toContain(SESSION);
+ expect(view).toContain("86 / 2728");
+ expect(view).toContain("3.2 s");
+ // Finished: the input is cleared for a follow-up on the same Session.
+ expect(h.state.input).toBe("");
+ expect(view).toContain(`placeholder="${S.agent.apiTryFollowUp}"`);
+
+ fetch.answer(() => sse([STARTED, RUN_DONE, "[DONE]"]));
+ h.dispatch({ type: "input", text: "And in Tokyo?" });
+ await runTry(TARGET, h.dispatch, tryBody(h.state), new AbortController().signal);
+ expect(fetch.requests[1]!.body).toEqual({ input: "And in Tokyo?", session_id: SESSION });
+ // A new run's output starts empty.
+ expect(rowsShown(h.state)).toEqual([
+ `1 run.started ${SESSION}`,
+ "2 run.done completed requests 2 output 86 total 2728",
+ ]);
+ });
+
+ it("marks a row still streaming as live while the run lasts, and a complete row not", () => {
+ const caret = 'data-live="caret"';
+ const mid = streaming([STARTED, text("It is "), text("09:30")]);
+ expect(tagged(html(mid), "api-try-row")[1]).toContain(caret);
+ // Arguments that do not parse yet show as received, and a call with none yet shows its tool.
+ const calling = streaming([
+ STARTED,
+ callFragment("call_1", "exec_command", '{"cmd": "da'),
+ callFragment("call_2", "read_file", ""),
+ ]);
+ expect(rowsShown(calling).slice(1)).toEqual([
+ '2 tool_call exec_command {"cmd": "da ▌',
+ "3 tool_call read_file ▌",
+ ]);
+ const done = streaming(TIME_RUN.slice(0, 13));
+ expect(tagged(html(done), "api-try-row").some((r) => r.includes(caret))).toBe(false);
+ // A run that ended mid-item leaves the item as it was, no longer live.
+ const ended = reduceTry(mid, { type: "ended" });
+ expect(tagged(html(ended), "api-try-row")[1]).not.toContain(caret);
+ expect(rowsShown(ended)[1]).toBe("2 text It is 09:30");
+ });
+
+ it("shows inline media as its type and size, never its bytes", () => {
+ const data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk";
+ const state = streaming([
+ STARTED,
+ {
+ type: "inline_data.done",
+ at: at(1),
+ role: "assistant",
+ mime_type: "image/png",
+ data,
+ stop_reason: "completed",
+ },
+ ]);
+ expect(rowsShown(state)[1]).toBe("2 inline_data image/png 45B");
+ expect(html(state)).not.toContain(data);
+
+ // Fragments of one inline item add up; an image input names a data URL's type and size,
+ // and any other URL as it is.
+ const media = streaming([
+ STARTED,
+ ...[data, data].map(
+ (d) =>
+ ({
+ type: "inline_data.delta",
+ at: at(1),
+ mime_type: "image/png",
+ data: d,
+ }) as unknown as AmspEvent,
+ ),
+ {
+ type: "image_url.done",
+ at: at(2),
+ role: "user",
+ image_url: `data:image/jpeg;base64,${data}`,
+ },
+ {
+ type: "image_url.done",
+ at: at(3),
+ role: "user",
+ image_url: "https://example.test/cat.png",
+ },
+ ]);
+ expect(rowsShown(media).slice(1)).toEqual([
+ "2 inline_data image/png 90B ▌",
+ "3 image_url image/jpeg 45B",
+ "4 image_url https://example.test/cat.png",
+ ]);
+ });
+
+ it("says on the row what sets an item apart: a text the harness sent, a call cut short, a result's images", () => {
+ const state = streaming([
+ STARTED,
+ {
+ type: "text.done",
+ at: at(1),
+ role: "user",
+ sender: "harness",
+ text: "Keep going.",
+ stop_reason: "completed",
+ },
+ {
+ type: "tool_call.done",
+ at: at(2),
+ tool_call_id: "call_1",
+ name: "exec_command",
+ arguments: '{"cmd":"sl',
+ stop_reason: "aborted",
+ },
+ {
+ type: "tool_result.done",
+ at: at(3),
+ tool_call_id: "call_2",
+ output: "Read 1 image.",
+ images: ["data:image/png;base64,AAAA"],
+ stop_reason: "completed",
+ },
+ ]);
+ expect(rowsShown(state).slice(1)).toEqual([
+ "2 text harness Keep going.",
+ '3 tool_call aborted exec_command {"cmd":"sl',
+ "4 tool_result images 1 Read 1 image.",
+ ]);
+ });
+
+ it("marks a child Session's rows with the chain they came from", () => {
+ const state = streaming([STARTED, text("Looking.", ["research", "sub-1"])]);
+ const [, child] = tagged(html(state), "api-try-row");
+ expect(child).toContain('data-tooltip="research/sub-1"');
+ expect(words(child!)).toBe("2 ↳ text Looking. ▌");
+ });
+
+ it.each([
+ [900, 120],
+ [900, 0],
+ [0, 0],
+ ])(
+ "shows cache read %i and cache write %i in the outcome strip, each only when not zero",
+ async (read, write) => {
+ const counts: TokenCounts = { cache_read: read, cache_write: write, output: 5, total: 50 };
+ stubFetch(() => sse([STARTED, { ...RUN_DONE, usage: counts }, "[DONE]"]));
+ const h = harness();
+ await runTry(TARGET, h.dispatch, tryBody(h.state), new AbortController().signal);
+ const strip = words(html(h.state).split('data-slot="foot"')[1] ?? "");
+ expect(strip).toContain("5 / 50");
+ for (const [label, n] of [
+ [S.agent.apiTryCacheRead, read],
+ [S.agent.apiTryCacheWrite, write],
+ ] as const) {
+ if (n > 0) expect(strip).toContain(`${label} ${n}`);
+ else expect(strip).not.toContain(label);
+ }
+ },
+ );
+
+ it("prints one numbered line per payload in the raw view, [DONE] last, and copies exactly them", async () => {
+ stubFetch(() => sse([...TIME_RUN, "[DONE]"]));
+ const h = harness();
+ await runTry(TARGET, h.dispatch, tryBody(h.state), new AbortController().signal);
+ const lines = [...TIME_RUN.map((e) => `data: ${JSON.stringify(e)}`), "data: [DONE]"];
+ expect(rawShown(h.state)).toEqual(lines.map((line, i) => `${i + 1} ${line}`));
+ expect(tagged(html(h.state, { view: "raw" }), "api-try-row")).toEqual([]);
+
+ const copies = find(ApiTryView(viewProps(h.state, { view: "raw" })), CopyButton).filter(
+ (c) => c.props.label === S.agent.apiTryCopyRaw,
+ );
+ expect(copies.map((c) => c.props.text)).toEqual([lines.join("\n")]);
+ });
+
+ it("shows a refusal before the stream as its status, code and message, with no rows", async () => {
+ stubFetch(() => apiError(409, "task_in_progress", "The Session is busy."));
+ const h = harness();
+ await runTry(TARGET, h.dispatch, tryBody(h.state), new AbortController().signal);
+ expect(h.state).toMatchObject({ running: false, rows: [], broken: false });
+ const view = html(h.state);
+ expect(view).toContain("409 task_in_progress — The Session is busy.");
+ expect(rowsShown(h.state)).toEqual([]);
+ expect(view).not.toContain(S.agent.apiTryStreamBroken);
+ });
+
+ it("says the stream broke when the body ends before run.done, keeping the rows so far", async () => {
+ stubFetch(() => sse(TIME_RUN.slice(0, 3)));
+ const h = harness();
+ await runTry(TARGET, h.dispatch, tryBody(h.state), new AbortController().signal);
+ expect(h.state).toMatchObject({ running: false, broken: true, result: null });
+ expect(rowsShown(h.state)).toHaveLength(3);
+ const view = html(h.state);
+ expect(view.indexOf(S.agent.apiTryStreamBroken)).toBeGreaterThan(
+ view.lastIndexOf('data-testid="api-try-row"'),
+ );
+ // The Session it named is kept: the next run can continue it.
+ expect(tryBody(h.state)).toMatchObject({ session_id: SESSION });
+ });
+
+ it("stops a run that named its Session through the Session's abort route, and shows the stream's run.done aborted", async () => {
+ let body: ReturnType<typeof live> | null = null;
+ const fetch = stubFetch((req) => {
+ if (req.path === TRY_PATH) {
+ body = live(req.signal);
+ body.send(STARTED, TIME_RUN[9]!, TIME_RUN[10]!);
+ return body.response;
+ }
+ if (req.path === `/api/sessions/${SESSION}/abort`) {
+ // The server aborts the run; its stream ends as it always does.
+ body!.send(
+ { type: "request.done", at: at(900), request: 2, status: "aborted", usage: null },
+ {
+ type: "run.done",
+ at: at(950),
+ status: "aborted",
+ error: { code: "user_abort", message: "Aborted by the user." },
+ requests: 2,
+ usage: usage(31, 1376),
+ session_usage: null,
+ },
+ "[DONE]",
+ );
+ body!.close();
+ return new Response(null, { status: 202 });
+ }
+ return apiError(404, "not_found");
+ });
+ const h = harness();
+ const connection = new AbortController();
+ const running = runTry(TARGET, h.dispatch, tryBody(h.state), connection.signal);
+ await vi.waitFor(() => expect(h.state.rows).toHaveLength(3));
+ expect(h.state.running).toBe(true);
+
+ await stopTry(h.state, connection);
+ await running;
+ expect(fetch.requests.map((r) => `${r.method} ${r.path}`)).toEqual([
+ `POST ${TRY_PATH}`,
+ `POST /api/sessions/${SESSION}/abort`,
+ ]);
+ expect(connection.signal.aborted).toBe(false);
+ expect(rowsShown(h.state).at(-1)).toContain("run.done aborted");
+ expect(h.state).toMatchObject({ running: false, broken: false, closed: true });
+ expect(h.state.result?.run.status).toBe("aborted");
+ });
+
+ it("stops a run that has not named its Session yet by aborting the request, with no error line", async () => {
+ const fetch = stubFetch(
+ (req) =>
+ new Promise<Response>((_resolve, reject) =>
+ req.signal?.addEventListener("abort", () => reject(req.signal!.reason)),
+ ),
+ );
+ // A continued conversation: the Session is known, but this run has not started on it.
+ const h = harness({ ...initialTryState("And now?"), sessionId: SESSION });
+ const connection = new AbortController();
+ const running = runTry(TARGET, h.dispatch, tryBody(h.state), connection.signal);
+ await vi.waitFor(() => expect(fetch.requests).toHaveLength(1));
+ // Waiting for the first event: the box holds the live caret and nothing else.
+ expect(html(h.state).split('data-testid="api-try-output"')[1]).toContain('data-live="caret"');
+
+ await stopTry(h.state, connection);
+ await running;
+ expect(fetch.requests[0]!.signal?.aborted).toBe(true);
+ expect(fetch.requests).toHaveLength(1);
+ expect(h.state).toMatchObject({ running: false, broken: false, error: null, rows: [] });
+ const view = html(h.state);
+ expect(view).not.toContain(S.agent.apiTryStreamBroken);
+ // The box is back to where it was before any run.
+ expect(view).toContain(S.agent.apiTryEmpty);
+ });
+
+ it("offers Allow and Deny on an approval row; an answer posts the decision and its buttons go", async () => {
+ let body: ReturnType<typeof live> | null = null;
+ const asked: AmspEvent = {
+ type: "approval.requested",
+ at: at(530),
+ tool_call: { tool_call_id: "call_1", name: "exec_command", arguments: '{"cmd":"date"}' },
+ };
+ const fetch = stubFetch((req) => {
+ if (req.path === TRY_PATH) {
+ body = live(req.signal);
+ body.send(STARTED, TIME_RUN[2]!, TIME_RUN[5]!, asked);
+ return body.response;
+ }
+ if (req.path === `/api/sessions/${SESSION}/approvals/call_1`) {
+ body!.send(
+ { type: "approval.decided", at: at(600), tool_call_id: "call_1", decision: "allow" },
+ ...TIME_RUN.slice(7),
+ "[DONE]",
+ );
+ body!.close();
+ return new Response(null, { status: 204 });
+ }
+ return apiError(404, "not_found");
+ });
+ const h = harness();
+ const running = runTry(TARGET, h.dispatch, tryBody(h.state), new AbortController().signal);
+ await vi.waitFor(() =>
+ expect(h.state.rows.at(-1)).toMatchObject({ type: "approval.requested" }),
+ );
+ expect(rowsShown(h.state).at(-1)).toContain("approval.requested exec_command");
+
+ const [row] = tagged(html(h.state), "api-try-row").filter((r) => r.includes("approval"));
+ expect(words(row!)).toContain(`${S.chat.approve} ${S.chat.deny}`);
+ const onApprove = vi.fn(async () => {});
+ const [decide] = approvalsOn(h.state, { onApprove });
+ await decide!("allow");
+ expect(onApprove).toHaveBeenCalledExactlyOnceWith("call_1", "allow");
+
+ await answerApproval(SESSION, "call_1", "allow", h.dispatch);
+ expect(fetch.requests.at(-1)).toMatchObject({
+ method: "POST",
+ path: `/api/sessions/${SESSION}/approvals/call_1`,
+ body: { decision: "allow" },
+ });
+ expect(approvalsOn(h.state)).toEqual([]);
+ await running;
+ expect(rowsShown(h.state)).toContain("5 approval.decided allow");
+ expect(h.state.result?.run.status).toBe("completed");
+ });
+
+ it("clears an approval's buttons when it was decided elsewhere, or when the run ended", () => {
+ const asked: AmspEvent = {
+ type: "approval.requested",
+ at: at(1),
+ tool_call: { tool_call_id: "call_1", name: "exec_command", arguments: "{}" },
+ };
+ const waiting = streaming([STARTED, asked]);
+ expect(approvalsOn(waiting)).toHaveLength(1);
+ const decided = reduceTry(waiting, {
+ type: "payload",
+ data: JSON.stringify({
+ type: "approval.decided",
+ at: at(2),
+ tool_call_id: "call_1",
+ decision: "deny",
+ }),
+ });
+ expect(approvalsOn(decided)).toEqual([]);
+ const ended = reduceTry(waiting, { type: "ended" });
+ expect(approvalsOn(ended)).toEqual([]);
+ });
+
+ it("forgets the Session and the output on New conversation, keeping the input", async () => {
+ stubFetch(() => sse([...TIME_RUN, "[DONE]"]));
+ const h = harness();
+ await runTry(TARGET, h.dispatch, tryBody(h.state), new AbortController().signal);
+ h.dispatch({ type: "input", text: "Again from the start" });
+
+ const onNewSession = vi.fn();
+ const [fresh] = buttonsNamed(h.state, S.agent.apiTryNewSession, { onNewSession });
+ (fresh!.props.onClick as () => void)();
+ expect(onNewSession).toHaveBeenCalledOnce();
+
+ h.dispatch({ type: "reset" });
+ expect(h.state).toMatchObject({
+ input: "Again from the start",
+ sessionId: null,
+ rows: [],
+ payloads: [],
+ result: null,
+ });
+ expect(tryBody(h.state)).toEqual({ input: "Again from the start" });
+ expect(html(h.state)).not.toContain(SESSION);
+ });
+});
diff --git a/packages/web/test/company-mode-write.test.ts b/packages/web/test/company-mode-write.test.ts
index e2c70049..848f85e3 100644
--- a/packages/web/test/company-mode-write.test.ts
+++ b/packages/web/test/company-mode-write.test.ts
@@ -22,6 +22,7 @@ const settings = (companyMode: boolean): ServerSettings => ({
attachmentMaxMb: 100,
attachmentTotalMb: 500,
companyMode,
+ agentApiEnabled: true,
});
/** Records what the switch sent and answers with the server's stored settings. */
diff --git a/packages/web/test/control-size.test.ts b/packages/web/test/control-size.test.ts
index f98b6409..563e1206 100644
--- a/packages/web/test/control-size.test.ts
+++ b/packages/web/test/control-size.test.ts
@@ -162,6 +162,7 @@ function findLooseFooterButtons(): string[] {
*/
const DIALOG_BODY_MODULES = new Set([
"features/settings/account-section.tsx",
+ "features/settings/agent-api-section.tsx",
"features/settings/profile-section.tsx",
"features/settings/appearance-section.tsx",
"features/settings/credits-section.tsx",
diff --git a/packages/web/test/helpers/fetch.ts b/packages/web/test/helpers/fetch.ts
index 1914ba88..0fdcccc1 100644
--- a/packages/web/test/helpers/fetch.ts
+++ b/packages/web/test/helpers/fetch.ts
@@ -22,6 +22,8 @@ export interface FetchRequest {
readonly query: URLSearchParams;
/** The body: parsed when it is JSON, as sent otherwise, undefined when there is none. */
readonly body: unknown;
+ /** The request's abort signal, for an answer that must end the way a real one does when it fires. */
+ readonly signal: AbortSignal | null;
}
export type FetchHandler = (request: FetchRequest) => Response | Promise<Response>;
@@ -48,6 +50,7 @@ export function stubFetch(handler: FetchHandler = () => apiError(404, "not_found
path: routed ? routed[2]! : parsed.pathname,
query: parsed.searchParams,
body: parseBody(init.body),
+ signal: init.signal ?? null,
};
requests.push(request);
return current(request);
diff --git a/packages/web/test/session-status-events.test.ts b/packages/web/test/session-status-events.test.ts
index 55c5f039..766d5ff5 100644
--- a/packages/web/test/session-status-events.test.ts
+++ b/packages/web/test/session-status-events.test.ts
@@ -342,6 +342,25 @@ describe("the full sequence, for a Session the user is not looking at", () => {
expect(glyph(store, "a", seen)).toBeNull();
});
+ it("a background Session shows the hourglass while it runs but never the unread dot", () => {
+ for (const source of ["api", "schedule", "subagent", "cli"] as const) {
+ const store = storeWith({ ...freshSession("bg"), source });
+ applyUserEvent(store, stateEvent("bg", "running", STARTED), neverReload);
+ expect(glyph(store, "bg", neverSeen)).toBe("running");
+ applyUserEvent(store, stateEvent("bg", "idle", FINISHED), neverReload);
+ expect(glyph(store, "bg", neverSeen)).toBeNull();
+ }
+ });
+
+ it("a person's conversation, marked or not yet known, still settles to the unread dot", () => {
+ for (const over of [{ source: "user" as const }, {}]) {
+ const store = storeWith({ ...freshSession("p"), ...over });
+ applyUserEvent(store, stateEvent("p", "running", STARTED), neverReload);
+ applyUserEvent(store, stateEvent("p", "idle", FINISHED), neverReload);
+ expect(glyph(store, "p", neverSeen)).toBe("completedUnread");
+ }
+ });
+
it("a Session the user opened earlier still goes unread when it later runs", () => {
const store = storeWith(session("a"));
const seen = seenAt("a", LOOKED);
diff --git a/packages/web/test/settings-sections.test.ts b/packages/web/test/settings-sections.test.ts
index 6ca0e070..be7b6994 100644
--- a/packages/web/test/settings-sections.test.ts
+++ b/packages/web/test/settings-sections.test.ts
@@ -56,6 +56,7 @@ describe("visibleSettingsSections", () => {
"proxy",
"uploads",
"company",
+ "agentApi",
"plugins",
"storage",
"users",
@@ -93,6 +94,7 @@ describe("visibleSettingsSections", () => {
"proxy",
"uploads",
"company",
+ "agentApi",
"plugins",
"storage",
]);
@@ -111,6 +113,7 @@ describe("visibleSettingsSections", () => {
"proxy",
"uploads",
"company",
+ "agentApi",
"plugins",
"storage",
]);
diff --git a/plugins/agent-development/package.json b/plugins/agent-development/package.json
index 3e4f7e3a..dcdcb267 100644
--- a/plugins/agent-development/package.json
+++ b/plugins/agent-development/package.json
@@ -1,7 +1,7 @@
{
"name": "@lmliheng/agent-development",
"version": "0.4.1",
- "description": "Agent development on Adelie: build on the SDK, call any model through one unified LLM API, manage models and secrets, and orchestrate agents, sessions, costs and schedules.",
+ "description": "Agent development on Adelie: build agent apps on the SDK or connect them to an agent over the Agent API, call any model through one unified LLM API, manage models and secrets, and orchestrate agents, sessions, costs and schedules.",
"license": "Apache-2.0",
"repository": {
"type": "git",
diff --git a/plugins/agent-development/plugin.json b/plugins/agent-development/plugin.json
index bdda819d..fdd851dd 100644
--- a/plugins/agent-development/plugin.json
+++ b/plugins/agent-development/plugin.json
@@ -1,8 +1,8 @@
{
- "description": "Agent development on Adelie: build on the SDK, call any model through one unified LLM API, manage models and secrets, and orchestrate agents, sessions, costs and schedules.",
- "description_zh": "基于 Adelie 的智能体开发:用 SDK 构建应用、经统一的 LLM API 调用任意模型、管理模型与密钥、编排智能体/会话/成本/定时任务。",
- "short_description": "SDK, unified LLM API, config and orchestration.",
- "short_description_zh": "SDK、统一 LLM API、配置与编排。",
- "version": "2026.10.07.1",
+ "description": "Agent development on Adelie: build agent apps on the SDK or connect them to an agent over the Agent API, call any model through one unified LLM API, manage models and secrets, and orchestrate agents, sessions, costs and schedules.",
+ "description_zh": "基于 Adelie 的智能体开发:用 SDK 构建应用或经 Agent API 接入智能体、经统一的 LLM API 调用任意模型、管理模型与密钥、编排智能体/会话/成本/定时任务。",
+ "short_description": "SDK, Agent API, unified LLM API, config and orchestration.",
+ "short_description_zh": "SDK、Agent API、统一 LLM API、配置与编排。",
+ "version": "2026.10.16.1",
"category": "ai-app-development"
}
diff --git a/plugins/agent-development/skills/penguin-orchestration/SKILL.md b/plugins/agent-development/skills/penguin-orchestration/SKILL.md
index 5d9a0368..8b7e8417 100644
--- a/plugins/agent-development/skills/penguin-orchestration/SKILL.md
+++ b/plugins/agent-development/skills/penguin-orchestration/SKILL.md
@@ -158,4 +158,5 @@ Prefer (a) when you stay around for the result — the completion report comes t
- **Unattended sessions must not need a human.** A spawned session inherits your approval mode (`allow-all` when there is no caller to inherit from); if you yourself run under `always-ask`, pass `--approve allow-all` (trusted work) or `--approve read-only` explicitly — an unattended `always-ask` session hangs waiting for approval in the web UI.
- **No runaway loops.** An agent that messages itself — directly, through a chain of agents, or through a schedule aimed back at its own session — keeps spending until someone stops it. Make every automated conversation terminate: a recurring schedule pointed at your own session takes an `--end-at` whenever the request has a natural horizon (or no `--period` at all, for a one-time reminder), and a prompt whose per-firing work stays small — that session's context grows with every firing. When the user wants it open-ended, leave `--end-at` off and tell them it runs until they remove it.
- **Spawned work bills the project.** Everything you start lands in the same project's usage (`penguin cost` shows it); a fan-out of sessions multiplies spend.
+- **Opening an agent to programs is the owner's call.** `penguin agent api` manages an agent's Agent API. Its `status` and `keys ls` only read. Never run `enable`, `disable`, `set`, `keys create`, `keys rm` or `server` yourself: the server refuses them to your token (`403 human_required`), and you must not sign in or mint a session to get past that. Ask the user to make the change on the agent's **API** tab, or in their own terminal after `penguin auth login`. To connect a program to an agent, use the penguin-sdk skill.
- **Configuration stays CLI-managed.** Never read or hand-edit `.project_config.toml` or `agent_state/.vault.toml` — models and secrets go through `penguin config` (see the penguin-cli skill).
diff --git a/plugins/agent-development/skills/penguin-sdk/SKILL.md b/plugins/agent-development/skills/penguin-sdk/SKILL.md
index 00de006e..fa1d5a0a 100644
--- a/plugins/agent-development/skills/penguin-sdk/SKILL.md
+++ b/plugins/agent-development/skills/penguin-sdk/SKILL.md
@@ -1,23 +1,87 @@
---
name: penguin-sdk
-description: Use whenever the user wants to build an agent application — their own program with an embedded agent, such as an AI app, an agentic app or a RAG app. This is writing application code on the Penguin Harness SDK, not configuring an Agent State inside Adelie. Covers self-contained projects, the createSession/run streaming loop with thinking and image messages, wiring the user's existing tools in as CLI commands, and a complete RAG recipe that ingests documents into a knowledge base and answers with citations behind a web UI. Also use it for workflows — the tabs and pages beside the chat that an Agent keeps in its own `workflows/` folder inside Adelie: building one, changing it, restoring an earlier version, and removing a tab or a whole workflow when the user wants the custom UI gone.
+description: Use whenever the user wants to build an agent application — their own program with an agent in it, such as an AI app, an agentic app, a RAG app or a bot — or to connect a program to an Adelie agent. A program reaches an agent in one of two ways, and the skill asks the user which before building — embedded with the Penguin Harness SDK (`@lmliheng/penguin-core`, no server), or over the Adelie server's Agent API (AMSP, with the `@lmliheng/amsp` client or curl). This is writing application code, not configuring an Agent State inside Adelie. Covers self-contained projects, the createSession/run streaming loop with thinking and image messages, wiring the user's existing tools in as CLI commands, a complete RAG recipe that ingests documents into a knowledge base and answers with citations behind a web UI, and the Agent API client. Also use it for workflows — the tabs and pages beside the chat that an Agent keeps in its own `workflows/` folder inside Adelie: building one, changing it, restoring an earlier version, and removing a tab or a whole workflow when the user wants the custom UI gone.
---
-# Penguin Harness SDK
+# Penguin Harness SDK and Agent API
-`@lmliheng/penguin-core` is the TypeScript SDK this agent itself runs on. Use it to build your own AI apps:
+This skill builds programs that use an Adelie agent. A program reaches one in either of two ways, embedded with the SDK or through the Adelie server's Agent API, and the user picks which. Workflows, at the end of this file, are a third thing: pages and server code an Agent keeps inside Adelie.
-- An **Agent** loads its state (prompts, tools, skills) from `<root>/<project_id>/agents/<agent_id>/`. Creating an Agent whose directory is empty initializes it with defaults.
-- A **Session** is one conversation of an Agent inside a **Workspace** directory.
-- `session.run()` executes one task and streams every step (thinking, text, tool calls) as OmniMessages.
+To have an agent perform a task for you, use the `run_subagent` tool: both ways are for programs, not for handing off your own work.
+
+## Two ways to reach an agent
+
+**The SDK: `@lmliheng/penguin-core`, embedded in the program.**
+
+- *What it is.* The agent loop as a TypeScript library. The program creates its own Agent from a data directory inside the project and runs its Sessions in-process. No Adelie server is involved, at build time or at run time.
+- *What you get.* The basic agent loop: the Agent State files (`AGENTS.md`, Skills, tools), the streamed OmniMessages and an `approve` callback for every tool call, in a self-contained folder that runs wherever Node 24 does, on the program's own model key.
+- *What you don't get.* No server-managed Sessions (the program keeps its own), no visibility in the Web App, no approvals UI (the program answers in code), no cost center and no sidebar Background folder. The embedded agent belongs to the program: changes to an Agent inside Adelie never reach it.
+- *Choose it when* the program must stand alone: shipped to other machines or people, run where no Adelie server is, or with the agent built into the product.
+
+**The API: Adelie's Agent API, over AMSP.**
+
+- *What it is.* The program calls an Agent that lives in Adelie, over HTTP. The Adelie server runs each turn and streams it back as AMSP events, and the program continues a conversation by its Session id. TypeScript uses the `@lmliheng/amsp` client (`AgentClient`); any other language, or curl, speaks HTTP and SSE directly.
+- *What you get.* The Agent as Adelie runs it: its `AGENTS.md`, Skills and memory, on the Project's models and credentials, so the program holds no model key. The server keeps the conversations in the Agent's Background folder, where a person can read them and answer approvals, and their usage lands in the cost center.
+- *What it requires.* A running Adelie server that the program can reach over the network; API access turned on for that Agent by the Project's owner, on the Agent's **API** tab; and a key created there, shown once. You never turn these on yourself (see *The API path*).
+- *Choose it when* the Agent already exists in Adelie or should be managed there, people need to see its conversations or costs, or the program is not written in TypeScript.
+
+### Ask which way first
+
+Whenever the user asks to connect a program to an agent, or to build a program with an agent in it (an AI, agentic or RAG app, a bot, a service, a script), ask which way before you write anything, even when the request is otherwise concrete. It is the only question a concrete request gets: it overrides the no-follow-up-questions default of *Before you start* for this one question.
+
+Do not ask when the way is already chosen:
+
+- in the user's message: "use the SDK", "standalone", "without the Adelie server" or "embed the agent" chooses the SDK; "call it over the API", "through the Agent API", "with AMSP", "with `@lmliheng/amsp`" or "with curl" chooses the API;
+- earlier in this conversation, for the same program.
+
+Naming this skill does not choose a way. Workflows (below) take neither way and need no question; neither does connecting a Feishu, Telegram, QQ or WeChat bot to a conversation, which is the Web App's Remote control.
+
+Ask with one sentence and this choice block, in the user's language, as the end of your reply. Mark one option `"recommended": true` only when the request leans that way: an Agent the user already has in Adelie leans to the API, an app to ship to others leans to the SDK.
-To have an agent perform a task, use the `run_subagent` tool — the SDK is for building applications, not for invoking agents.
+````markdown
+Your program can reach the agent in two ways: embedded with the SDK, or through the Adelie server's Agent API.
+
+```a2ui
+{
+ "type": "choice",
+ "id": "agent-access",
+ "question": "How should the program reach the agent?",
+ "options": [
+ {
+ "label": "SDK: embed the agent",
+ "value": "Use the SDK: embed the agent in the program",
+ "description": "Runs inside the program on its own model key. No Adelie server; nothing appears in the Web App."
+ },
+ {
+ "label": "API: call an Adelie Agent",
+ "value": "Use the Agent API: call an Adelie Agent over AMSP",
+ "description": "Calls an Agent on your Adelie server. You turn on its API access and create a key; its conversations appear in the Web App."
+ }
+ ]
+}
+```
+````
+
+The Web App shows the block as two buttons; the CLI and the messaging channels show it as a numbered list. The answer arrives as the user's next message, in plain text: read it like any other message and build on the way it names.
## Before you start
-If the user's message only invokes this skill (e.g. "use penguin-sdk skill") without a concrete app to build, ask the user what they want to build. But when the request names a concrete goal — even a single sentence like "build a RAG app that answers questions about these docs" — do **not** ask follow-up questions: build it end to end with the defaults in this skill (self-contained workspace project, project default model, BM25 retrieval, web UI styled per the web-design skill) and list the assumptions you made in your final reply.
+If the user's message only invokes this skill (e.g. "use penguin-sdk skill") without a concrete app to build, ask the user what they want to build. Once the request is concrete, settle the way first (see *Ask which way first*); a workflow needs none. Then do **not** ask follow-up questions: build it end to end with that way's defaults and list the assumptions you made in your final reply.
+
+- SDK path: a self-contained workspace project, the project default model, BM25 retrieval, a web UI styled per the web-design skill.
+- API path: a self-contained workspace project in TypeScript on `@lmliheng/amsp` (plain HTTP when the user's program is in another language), calling the Agent the user named ("you" means this Agent) or, with none named, a new Agent created for the purpose with the agent-initialization skill.
+
+Each path also needs one thing only the user can provide: a model credential on the SDK path (see *Keys and the data root*), and on the API path the Agent's API access and key (see *The API path*).
+
+## The SDK path
+
+`@lmliheng/penguin-core` is the TypeScript SDK this agent itself runs on. Use it to build your own AI apps:
+
+- An **Agent** loads its state (prompts, tools, skills) from `<root>/<project_id>/agents/<agent_id>/`. Creating an Agent whose directory is empty initializes it with defaults.
+- A **Session** is one conversation of an Agent inside a **Workspace** directory.
+- `session.run()` executes one task and streams every step (thinking, text, tool calls) as OmniMessages.
-## Project location
+### Project location
Create the app in the current workspace directory by default (the `CWD` value from your Environment section), as a self-contained project — do not place it under `<app_data_dir>` (Adelie's app data root) or depend on any path outside the project folder. When creating the app's agent, the data root defaults **under the working directory (CWD)** too: point `createAgent({ root })` at a directory inside the project, resolved from the source file so it stays relative:
@@ -27,7 +91,7 @@ const agent = await createAgent({ root: path.join(import.meta.dirname, "penguin_
With every reference relative to the project, the user can move or copy the folder anywhere and it still runs.
-## Keys and the data root — check before you build
+### Keys and the data root — check before you build
**The app's Penguin data root must live inside the CWD workspace — never `~/.adelie`.** Point `createAgent({ root })` and every `penguin config ... --root <dir>` at a directory under the current working directory (e.g. `./penguin_data`); the global `~/.adelie` belongs to the person running Penguin and must never hold — or lend — the app's config or keys.
@@ -41,7 +105,7 @@ env | grep -oE "(DEEPSEEK|OPENAI|ANTHROPIC|GEMINI)_API_KEY" || echo none
If neither counted source yields a key, **stop immediately and ask the user to configure one — do not start building, and do not burn turns re-checking in a loop**: have them open this agent's settings via the **gear icon** on its card (left side, Agents page) and add a model API key (e.g. `DEEPSEEK_API_KEY`) in the **key vault** tab — vault values reach your shell environment on the next task. One clear check, then hand back to the user. Build only after a credential is confirmed, or after clearly agreeing with the user to build now and verify later. Model ids to offer the user come from the penguin CLI catalog (`penguin config model add --help`) and the agenthub-models skill's id table.
-## Setup
+### Setup
```bash
npm install @lmliheng/penguin-core tsx
@@ -60,7 +124,7 @@ Model config lives in one hidden file under the data root's project directory: `
If the user agreed to build before a credential exists, do not fake the verification: finish the build, report it as **unverified**, and point them at the key vault flow above — once a key is added, vault values reach your environment on the next task and you can run the self-test to completion.
-## Streaming loop
+### Streaming loop
The raw `run()` stream mixes model, event and session-meta payloads — always narrow with the exported guards (`isModelMessage`, `isCompleteModelMessage`, `isEventMessage`) before touching `payload.type`; accessing `msg.payload.type` directly does not typecheck.
@@ -99,7 +163,7 @@ session.dispose();
- Session lifetime is the app's memory model: reuse one Session for a stateful chat (context accumulates, as above), create one per request for stateless QA (the RAG recipe below); either way call `session.dispose()` when done to release background processes.
- An Agent's behavior is edited in its `agent_state/` files (system_config.yaml, AGENTS.md, skills/), not in code.
-## Thinking and image messages
+### Thinking and image messages
Modern models think before answering and accept images; the stream and the input protocol carry both — use them instead of flattening everything to text.
@@ -116,13 +180,13 @@ Browser flow: `<input type="file" accept="image/*">` plus paste/drag-drop → `F
**Other payloads worth handling** (always narrow with the guards first): `partial_tool_call` / `partial_tool_call_output` — surface as an activity line ("running `search`…") in apps that grant tools; `request_end` (event) — a non-`completed` `status` is the error signal (`auth` → ask for a key; `message` carries the failure detail; `retry_in_ms` announces a planned in-run retry, renderable as a countdown); `token_usage` (event) — session-cumulative and last-request counts, if the app shows cost; `compaction_begin` / `compaction_end` (events) — long-lived chats only, show a brief "context being compacted" notice. Everything else is safe to ignore.
-## Wiring in the user's tools
+### Wiring in the user's tools
When the app's agent must call the user's existing tools (scripts, internal CLIs, anything with an entry point), integrate them as **CLI commands** first: wrap each one as a small executable inside the project (a script under `tools/`, or the user's own binary), and describe it in the embedded agent's persona / `AGENTS.md` — name, what it does, one usage line. The agent invokes it through the built-in `exec_command` tool, so there is nothing to register: no schema to declare, arguments are flags, stdout is the result, the `approve` callback still gates every invocation, and the same command stays testable by hand.
Add an MCP server (`tools.mcpServers` in `system_config.yaml`) only when a CLI wrapper cannot express the integration — a long-lived authenticated connection, or tool schemas the model must see typed. Otherwise the CLI form is the cheaper default and keeps the project self-contained.
-## RAG knowledge app
+### RAG knowledge app
The default recipe when the user wants an app that answers questions over a document set ("docs QA", "knowledge base", "chat with our docs", "become an expert on X"). The core contributes the agent loop only — retrieval is app code. Default to **lexical BM25**: no extra dependencies, no embedding credential, works offline. (Semantic upgrade: embed chunks via `@prismshadow/agenthub` — see the agenthub-models skill — and rank by cosine; only when an embedding-capable key is configured.)
@@ -344,6 +408,29 @@ http.createServer(async (req, res) => {
**Persona** (`persona.md`) — the embedded agent's role, written per the agent-initialization skill. Shape: one role sentence ("You are an expert on X; you answer strictly from the provided context blocks"), citation and refusal rules, plain-text output (no Markdown — the output contract above), answer language follows the question.
+### Verify before you hand over
+
+Never declare the app done without running it:
+
+1. `npm install` succeeds (or the workspace route builds).
+2. Model configured for `penguin_data` (CLI or env var; no usable key → see Setup: ask the user to add one to this agent's key vault, and report the app as unverified for now).
+3. `npm run ingest` prints `indexed N chunks` with N > 0.
+4. Start `npm start` in the background, then ask a real question:
+ `curl -N -sS -X POST localhost:4630/api/ask -H 'content-type: application/json' -d '{"question":"<something the corpus answers>"}'` — expect streamed `data:` deltas ending in a `sources` event that carries `source`, `url` **and the matched chunk `text`** per hit. If nothing streams, the model call failed: re-check step 2 and the provider endpoint before touching the code.
+ Then `curl` one of the returned source `url`s — it must return the document, not a 404 (citation links have to resolve).
+5. Open the UI (or screenshot it) to confirm the layout renders.
+
+Fix any failure and re-verify; when the app accepts image input, one verification question must include a real image. Report with backtick-wrapped relative paths (`server.ts`, `public/index.html`, …), how to start the app, and the assumptions you made.
+
+## The API path
+
+The program calls an Agent that lives in Adelie. You write the program; the Project's owner opens the Agent to it. Read [`reference/agent-api.md`](reference/agent-api.md) before you write any code: it has the steps to hand the owner, the client code, curl, the errors and the checks. These rules hold throughout:
+
+- **Never open an Agent yourself.** Whether an Agent is open to programs is the owner's decision, and so is everything around it: API access, keys, keyless access, the API approval mode and the server-wide switch. An Agent must not be able to expose itself. The server refuses `penguin agent api enable`, `disable`, `set`, `keys create`, `keys rm` and `server` to the token in your shell with `403 human_required`, because they take a person's sign-in. Never run them, and never sign in or mint a session to get past that refusal. Ask the user to make the change on the Agent's **API** tab, or with those commands in their own terminal after `penguin auth login`, and give them the steps. `penguin agent api status` and `keys ls` only read; use them to check.
+- **Keep the key out of the code.** The program reads it from the `ADELIE_AGENT_KEY` environment variable. Never write a key into source, a committed file, a log or a reply, and never ask the user to paste one into the chat.
+- **Connection values.** The Base URL and the Agent ID come from the API tab or `penguin agent api status --agent-id <agentId>`. A local server's Base URL is `http://localhost:7364/api/amsp/v1`: `localhost`, not `127.0.0.1`, where a local server serves previews and refuses every API request with `401`. The Agent ID is `<projectId>/<agentId>`.
+- **No data root, no model key.** The server runs the Agent on the Project's models. An SDK recipe keeps its shape on this path: the RAG app, for instance, replaces `createAgent`, `createSession` and `session.run` with an `AgentClient` run, and its persona goes into the Agent's `AGENTS.md`.
+
## Workflows: pages and server code the Agent keeps for itself
Inside Adelie an Agent can hold *workflows*: small plugin packages in its own directory, written in TypeScript, that the server boots as module trees, shows as tabs beside the chat, reloads on every file change, and versions so any edit can be undone. This is the same module mechanism the server itself is built from — manifests as data, everything checked before any code runs — so a workflow that does not type-check, that was written against an interface version this server no longer fits, or whose manifests do not hold together fails to load with the problem named, while the previous version keeps serving.
@@ -447,17 +534,3 @@ Your handler's responses are served from the app's own origin, so anything you e
**Theme.** A workflow page is a separate document, so it inherits nothing from the app's stylesheet by itself. The Web App stamps `light`/`dark` on the page's root, copies its resolved palette (the gray scale, the accent pair, the font stack, the root font size) onto it, and injects `/workflow-ui.css` first in the head — a base stylesheet that styles plain HTML (headings, lists, forms, tables, code) to match the app and exposes `--wf-bg`, `--wf-fg`, `--wf-muted`, `--wf-border`, `--wf-surface`, `--wf-accent`, `--wf-accent-fg`, plus the classes `wf-primary` (a button), `wf-card`, `wf-rows`, `wf-row`, `wf-muted`. Write plain markup, take every colour and font from those variables, and the page follows the user through a theme or accent change; hardcode them and it clashes in one theme or the other. The page's own rules always win, and linking `/workflow-ui.css` yourself makes it look right when opened outside the app too.
**Filling the app.** A page can be shown as the whole app — no sidebar, no chat, no tab strip — at `/app/<project>/<agent>/<workflow>[/<tab key>]` (the workflow's first tab when no key is given): the tab's *Fill the app* button goes there, `penguin web --app <project>/<agent>/<workflow>[/<tab key>]` opens the browser straight onto it, and the page itself can ask with `parent.postMessage({ type: "penguin:fill-app" }, "*")`. The way back is the command palette — Ctrl+P or Ctrl+Shift+P (⌘ on macOS), both, so a page may take one of them for itself but never both — whose *Exit full page* lands on that Agent's chat.
-
-## Verify before you hand over
-
-Never declare the app done without running it:
-
-1. `npm install` succeeds (or the workspace route builds).
-2. Model configured for `penguin_data` (CLI or env var; no usable key → see Setup: ask the user to add one to this agent's key vault, and report the app as unverified for now).
-3. `npm run ingest` prints `indexed N chunks` with N > 0.
-4. Start `npm start` in the background, then ask a real question:
- `curl -N -sS -X POST localhost:4630/api/ask -H 'content-type: application/json' -d '{"question":"<something the corpus answers>"}'` — expect streamed `data:` deltas ending in a `sources` event that carries `source`, `url` **and the matched chunk `text`** per hit. If nothing streams, the model call failed: re-check step 2 and the provider endpoint before touching the code.
- Then `curl` one of the returned source `url`s — it must return the document, not a 404 (citation links have to resolve).
-5. Open the UI (or screenshot it) to confirm the layout renders.
-
-Fix any failure and re-verify; when the app accepts image input, one verification question must include a real image. Report with backtick-wrapped relative paths (`server.ts`, `public/index.html`, …), how to start the app, and the assumptions you made.
diff --git a/plugins/agent-development/skills/penguin-sdk/reference/agent-api.md b/plugins/agent-development/skills/penguin-sdk/reference/agent-api.md
new file mode 100644
index 00000000..935e36be
--- /dev/null
+++ b/plugins/agent-development/skills/penguin-sdk/reference/agent-api.md
@@ -0,0 +1,159 @@
+# The API path: a program that calls an Adelie Agent
+
+Read this before you write a program that calls an Adelie Agent over the Agent API. The rules in SKILL.md, *The API path*, hold throughout. The user documentation has every detail: the [Agent API guide](https://penguin.ooo/docs/agent-api) and the [AMSP protocol](https://penguin.ooo/docs/amsp).
+
+## 1. Hand the opening to the user
+
+Check first. This command only reads:
+
+```bash
+penguin agent api status --agent-id <agentId> --json
+```
+
+It prints one line of JSON: `agent` (the Agent ID), `baseUrl`, `api` (`enabled`, `open`, `approvalMode`, `keys`) and `serverEnabled`. A key's secret is never in it.
+
+When `api.enabled` is false, or `api.keys` is empty and `api.open` is false, the program cannot run yet. Give the user these steps with the Agent's id filled in. Only the Project's owner can take them.
+
+1. Open the Agent's settings and select the **API** tab (`/agents/<agentId>?tab=api`).
+2. Turn on **Enable API access**.
+3. Choose the **Approval mode for API conversations** (see the table below).
+4. Under **Keys**, select **New key**, name it after the program, and copy the key. It is shown once.
+5. Give the key to the program as the environment variable `ADELIE_AGENT_KEY`.
+
+The same steps in the user's own terminal, never in yours:
+
+```bash
+penguin auth login
+penguin agent api enable --agent-id <agentId> --approve <mode>
+export ADELIE_AGENT_KEY="$(penguin agent api keys create --agent-id <agentId> --name <program>)"
+```
+
+`keys create` prints the key alone on stdout, so the variable takes it without showing it. These commands change the Agent's exposure, so they take the user's sign-in: `penguin auth login` once, or `penguin auth token` on the server's machine. From your shell the server refuses them with `403 human_required`. Never sign in or mint a session to get past that.
+
+When `serverEnabled` is false, the server's administrator has turned the Agent API off, and every request is refused with `403`. Only an administrator turns it back on, in **Settings › Server › Agent API**.
+
+Suggest the approval mode that fits the program, and say why in one line:
+
+| The program | Mode | What happens |
+| --- | --- | --- |
+| Has no one to ask: a batch job, a backend | `allow-all` (the default) | Every tool call runs, inside the sandbox |
+| May let the agent read but nothing more | `read-only` | Read-only tools run; every other call waits for the program's answer |
+| Shows every tool call to its own user | `always-ask` | Every call waits for the program's answer |
+| Must never run a tool | `deny-all` | Every call is denied; the agent answers without tools |
+
+A call that waits reaches the program as an `approval.requested` event, and the run waits, with no time limit, for an answer, an abort or a disconnect. The `@lmliheng/amsp` client answers it with `onApproval`, or with `deny` when there is none. The mode is read when an API conversation is created; a change on the tab applies to conversations created after it.
+
+Leave **Allow keyless access** off unless the user asks for it. With it on, anything that can reach the server can run the Agent on the Project's models.
+
+To run the program yourself, you need the key in your environment. Ask the user to add it to your key vault as `ADELIE_AGENT_KEY`: the gear icon on your card on the Agents page, then the key vault tab. Vault values reach your shell on the next task. Until then, the program is unverified.
+
+## 2. The connection values
+
+| Value | Where it comes from | In the program |
+| --- | --- | --- |
+| Base URL | **Connection** on the API tab, or `baseUrl` from `status` | A constant, which `ADELIE_AGENT_URL` can override |
+| Agent ID | **Connection** on the API tab, or `agent` from `status`: `<projectId>/<agentId>` | A constant |
+| Key | Created by the owner, shown once | `process.env.ADELIE_AGENT_KEY`, and nowhere else |
+
+- A local server's Base URL is `http://localhost:7364/api/amsp/v1`; `status` prints the server's real port. Use `localhost`, never `127.0.0.1`: a local server serves previews on `127.0.0.1` and answers every API request there with `401`.
+- Do not give the program's settings the names the harness sets inside a session: `ADELIE_API_URL`, `ADELIE_API_TOKEN`, `ADELIE_PROJECT_ID`, `ADELIE_AGENT_ID`, `ADELIE_SESSION_ID`. They name the session's own server and Agent, and they override a vault entry of the same name.
+
+## 3. TypeScript: `@lmliheng/amsp`
+
+```bash
+npm install @lmliheng/amsp
+```
+
+The client has no dependencies and runs in Node 24 and in current browsers. If your registry does not have the package, call the API over HTTP as in section 4.
+
+```ts
+import { AgentClient, parseArguments } from "@lmliheng/amsp";
+
+const apiKey = process.env.ADELIE_AGENT_KEY;
+if (!apiKey) throw new Error("Set ADELIE_AGENT_KEY to the key from the agent's API tab.");
+
+const client = new AgentClient({
+ baseUrl: process.env.ADELIE_AGENT_URL ?? "http://localhost:7364/api/amsp/v1",
+ agent: "demo/coder", // <projectId>/<agentId>
+ apiKey, // the client reads no environment variable itself
+});
+
+// One question, the whole answer.
+const first = await client.ask({ input: "Summarize README.md" });
+if (first.status !== "completed") throw new Error(`${first.status}: ${first.error?.message ?? ""}`);
+console.log(first.text);
+
+// The same conversation, streamed: pass its Session id back.
+const run = client.run({
+ sessionId: first.sessionId,
+ input: "Now list its headings",
+ onApproval: (request) => {
+ const args = parseArguments(request.tool_call);
+ return request.tool_call.name === "exec_command" && args?.command === "ls" ? "allow" : "deny";
+ },
+});
+for await (const event of run) {
+ // An event without `origin` is the main conversation's; a subagent's events carry one.
+ if (event.type === "text.delta" && !event.origin) process.stdout.write(event.text);
+}
+const second = await run.result();
+```
+
+- `ask()` runs to the end and resolves with the result: `status`, `error`, `sessionId`, `text` (the main conversation's answer), `items`, `usage`, `sessionUsage` and `requests`. `run()` starts the run and returns it at once: iterate it once for the events, await `run.session` for the Session id, and `run.result()` for the end.
+- **Conversations.** Keep one `sessionId` per conversation of the program, such as one per end user or chat thread, and pass it back to continue. Omit it to start a new conversation. Only the Agent's own API conversations can be continued.
+- **Approvals.** `onApproval` is called only when the approval mode makes a call wait. Without it, or when it throws, the client answers `deny`. A person can answer the same request in the Web App; the first answer counts.
+- **Aborting.** Abort the `signal` passed to `run()` or `ask()` to drop the connection: the server aborts the run. `run.abort()` asks the server to abort and still delivers the final `run.done`, with `status: "aborted"`.
+- **Failures.** A refusal before the stream starts rejects with `AmspHttpError` (`status`, `code`, `message`; see section 5). After that, `result()` resolves for every run: check `status` (`completed`, `aborted`, `retryable` or `fatal`) and `error`. A stream that breaks before `run.done` rejects with `AmspStreamError`.
+- **Unknown events** are passed through. Switch on `event.type` with a default branch.
+- **A web app** keeps the key on its own server. The page posts to the app's server, which runs the Agent and relays the `text.delta` events to the page over SSE, aborting through `signal` when the page disconnects: the shape of the RAG recipe's `server.ts`. A key inside a page is readable by everyone who loads the page.
+
+## 4. Any language: HTTP and curl
+
+```bash
+BASE="${ADELIE_AGENT_URL:-http://localhost:7364/api/amsp/v1}"
+
+# Start a conversation. The answer streams back as it is produced.
+curl -N "$BASE/agents/demo/coder/runs" \
+ -H "Authorization: Bearer $ADELIE_AGENT_KEY" -H "Content-Type: application/json" \
+ -d '{"input":"Summarize README.md"}'
+
+# Continue it with the session_id that the first event, run.started, carried.
+curl -N "$BASE/agents/demo/coder/runs" \
+ -H "Authorization: Bearer $ADELIE_AGENT_KEY" -H "Content-Type: application/json" \
+ -d '{"session_id":"<session_id>","input":"Now list its headings"}'
+
+# Answer an approval.requested event while its run is still streaming.
+curl -X POST "$BASE/sessions/<session_id>/approvals/<tool_call_id>" \
+ -H "Authorization: Bearer $ADELIE_AGENT_KEY" -H "Content-Type: application/json" \
+ -d '{"decision":"allow"}'
+```
+
+To read the stream in your own code:
+
+- Each event is one `data: <JSON>` line followed by a blank line. After the last event comes `data: [DONE]`. A line that starts with `:` is a keep-alive comment, sent after 15 seconds of silence: skip it.
+- The first event is `run.started`, with the `session_id`. The last is `run.done`, with `status`, `error` and `usage`. The answer is the assistant `text.done` events without an `origin`, or their `text.delta` fragments as they arrive.
+- Skip every event `type` you do not know.
+- `POST <Base URL>/sessions/<session_id>/abort` aborts a run and keeps its stream open until `run.done`.
+
+## 5. Errors
+
+A request refused before the stream gets an HTTP status and `{"error": {"code": "…", "message": "…"}}`. Once the stream has started, `run.done` carries the error instead.
+
+| Status | `code` | Usually | What to do |
+| --- | --- | --- | --- |
+| 400 | `bad_request` | A malformed body | The message names the field |
+| 401 | `unauthorized` | No key, a wrong or deleted key, or `127.0.0.1` in the Base URL | Check `ADELIE_AGENT_KEY` and that the Base URL uses `localhost` |
+| 403 | `agent_api_disabled` | The administrator turned the Agent API off | Ask the user to have an administrator turn it on |
+| 404 | `agent_not_found` | API access is off, the Agent ID is wrong, or the key belongs to another Agent | Check with `penguin agent api status`, then ask the owner |
+| 404 | `session_not_found` | The `session_id` is not one of this Agent's API conversations | Start a new conversation |
+| 409 | `task_in_progress`, `compacting` | The conversation is still busy | Wait for its `run.done`: one run per conversation at a time |
+| 429 | `too_many_runs` | The Agent already has 4 API runs going | Retry after `Retry-After` seconds |
+
+## 6. Verify before you hand over
+
+1. `penguin agent api status --agent-id <agentId> --json` shows `api.enabled` true and at least one key.
+2. The key is in your environment: `test -n "$ADELIE_AGENT_KEY" && echo set`. Never print the value.
+3. Run the program once with a real input. The run ends with `status` `completed`, and the answer appears.
+4. Tell the user where to find the conversation: the Agent's **Background** folder in the sidebar, marked with the API icon.
+
+When step 1 or 2 is not done, finish the program anyway, report it as **unverified**, and end your reply with the owner's steps from section 1. Report the files with relative paths, how to run the program, the Agent ID it calls, the approval mode it expects, and your assumptions.
diff --git a/plugins/agent-tuning/plugin.json b/plugins/agent-tuning/plugin.json
index 9f3cc9be..a440c7b4 100644
--- a/plugins/agent-tuning/plugin.json
+++ b/plugins/agent-tuning/plugin.json
@@ -1,8 +1,8 @@
{
- "description": "Agent tuning as a loop: initialize an agent from a requirement, design and calibrate a capability benchmark, run and score isolated cases, and improve the agent from measured results.",
- "description_zh": "闭环的 Agent 调优:依据需求初始化 Agent、设计并校准能力 Benchmark、隔离执行与评分、再根据测得结果改进 Agent。",
- "short_description": "Initialize, benchmark, evaluate and improve agents.",
- "short_description_zh": "初始化、评测、评分与改进 Agent。",
- "version": "2026.10.10.1",
+ "description": "Agent tuning as a loop: initialize an agent from a requirement — for people in the app, or for a program to reach over the Agent API — design and calibrate a capability benchmark, run and score isolated cases, and improve the agent from measured results.",
+ "description_zh": "闭环的 Agent 调优:依据需求初始化 Agent(供人使用,或供程序经 Agent API 接入)、设计并校准能力 Benchmark、隔离执行与评分、再根据测得结果改进 Agent。",
+ "short_description": "Initialize, benchmark, evaluate and improve agents, for people or over the Agent API.",
+ "short_description_zh": "初始化、评测、评分与改进 Agent:给人用,或经 Agent API 供程序接入。",
+ "version": "2026.10.16.1",
"category": "ai-app-development"
}
diff --git a/plugins/agent-tuning/skills/agent-initialization/SKILL.md b/plugins/agent-tuning/skills/agent-initialization/SKILL.md
index 6cd44aa3..f9cadbbe 100644
--- a/plugins/agent-tuning/skills/agent-initialization/SKILL.md
+++ b/plugins/agent-tuning/skills/agent-initialization/SKILL.md
@@ -1,6 +1,6 @@
---
name: agent-initialization
-description: Initialize or extend an Agent from a user requirement - write AGENTS.md, set identity metadata, and create, install or import Skills and hook packages (scripts the harness runs on every prompt, before tool calls, or after a task).
+description: Initialize or extend an Agent from a user requirement - write AGENTS.md, set identity metadata, and create, install or import Skills and hook packages (scripts the harness runs on every prompt, before tool calls, or after a task). For an agent that a program will use, it first asks whether the program embeds the agent with the SDK or calls it over the Agent API.
---
# Agent Initialization
@@ -11,6 +11,50 @@ This skill initializes an agent's settings from a user requirement — plain fil
If the user's message only invokes this skill (e.g. "use agent-initialization skill") without a concrete requirement, ask the user what agent they want and what it should do. But when the requirement is already concrete — even a single sentence like "an expert that answers questions about X" — do **not** ask follow-up questions: derive the role and rules from that sentence, apply the defaults below, and list your assumptions in the final reply.
+One question comes first even then: when the agent is for a program to use, ask how the program reaches it before you create anything (see *An agent for a program*).
+
+## An agent for a program
+
+A program — an app, a service, a bot, a script — reaches an Adelie agent in one of two ways, and they put the agent in different places:
+
+- **The SDK** (`@lmliheng/penguin-core`): the agent is embedded in the program and runs without the Adelie server, on the program's own model key. No Agent is created in this Project; the agent lives in the program's own data directory (see *The embedded agent of an SDK app*). The program gets no server-managed Sessions, no Web App visibility, no approvals UI and no cost center.
+- **The API** (Adelie's Agent API, over AMSP): the program calls an Agent of this Project through the running server, which keeps the conversations in the Agent's Background folder. You create or configure that Agent here as usual; the Project's owner then turns on its API access and creates a key for the program.
+
+Whenever the requested agent is for a program, ask which way before you create anything, even when the requirement is otherwise concrete. It is the one exception to the no-follow-up-questions default above. Do not ask when the user has already chosen ("embed it with the SDK", "call it over the API") or answered earlier in this conversation. An agent that people talk to, in the Web App, the CLI or a Remote-control bot, is not for a program and needs no question.
+
+Ask with one sentence and this choice block, in the user's language, as the end of your reply:
+
+````markdown
+Your program can reach the agent in two ways: embedded with the SDK, or through the Adelie server's Agent API.
+
+```a2ui
+{
+ "type": "choice",
+ "id": "agent-access",
+ "question": "How should the program reach the agent?",
+ "options": [
+ {
+ "label": "SDK: embed the agent",
+ "value": "Use the SDK: embed the agent in the program",
+ "description": "Runs inside the program on its own model key. No Adelie server; nothing appears in the Web App."
+ },
+ {
+ "label": "API: call an Adelie Agent",
+ "value": "Use the Agent API: call an Adelie Agent over AMSP",
+ "description": "Calls an Agent on your Adelie server. You turn on its API access and create a key; its conversations appear in the Web App."
+ }
+ ]
+}
+```
+````
+
+The Web App shows the block as two buttons; the CLI and the messaging channels show it as a numbered list. The answer arrives as the user's next message, in plain text. Then hand over by the way it names:
+
+- **SDK:** build the program with the penguin-sdk skill, and apply this skill to the program's embedded agent instead of creating an Agent here.
+- **API:** create or configure the Agent with the rest of this skill. Never turn on its API access or create its keys yourself: an Agent must not be able to expose itself. The server refuses those changes to the token in your shell (`403 human_required`); never sign in or mint a session to get past that. In your report, give the user the steps. On the Agent's **API** tab (`/agents/<agentId>?tab=api`), turn on **Enable API access**, choose the approval mode for API conversations, and create a key under **Keys**; it is shown once, and the program reads it from `ADELIE_AGENT_KEY`. Or, in their own terminal, run `penguin auth login`, then `penguin agent api enable --agent-id <agentId>` and `penguin agent api keys create --agent-id <agentId> --name <program>`. Name the Agent ID, `<projectId>/<agentId>`, and the Base URL: `http://localhost:7364/api/amsp/v1` on a local server, with `localhost`, not `127.0.0.1`. For the program itself, follow the penguin-sdk skill's API path (`reference/agent-api.md`).
+
+If you do not have the penguin-sdk skill, read it from `default_agent`'s `agent_state/skills/penguin-sdk/`, or ask the user to install the `agent-development` plugin from the Plugins page.
+
## Resolve the inherited runtime
Treat the current Agent as the **Builder**. Resolve the runtime before creating a new Agent:
@@ -70,7 +114,7 @@ Do not register Skills in AGENTS.md; the frontmatter is injected automatically.
Common library bundles, so you don't under-equip the target:
- **App builder** (builds apps or web frontends): `penguin-sdk`, `web-design`, `agenthub-models`.
-- **Knowledge expert** (answers questions over a document set): usually **no** harness agent is needed — build a RAG app with the penguin-sdk skill instead, and configure the app's embedded agent (below).
+- **Knowledge expert** (answers questions over a document set): usually a RAG app built with the penguin-sdk skill rather than a harness agent alone. The app reaches its agent by one of the two ways above: on the SDK path, configure the app's embedded agent (below); on the API path, the Agent you create here.
- **Evaluation loop**: `benchmark-design`, `agent-evaluation`, `agent-optimization`.
When creating a Test Agent, install only the capabilities it needs to solve ordinary tasks.
@@ -165,8 +209,8 @@ Before finishing:
- confirm every installed hook package has a `hooks.json` that parses, that each command it lists is a file inside the package, and that each script ran by hand exits 0 and prints JSON or nothing;
- confirm no Agent outside `TARGET` was changed.
-Report the target path, whether an existing Agent was configured or a new Agent was created, assumptions, installed Skills and hook packages (for each hook: what it does and at which point it fires), when the change takes effect, the resolved runtime and whether each value was user-specified or inherited, and validation results.
+Report the target path, whether an existing Agent was configured or a new Agent was created, assumptions, installed Skills and hook packages (for each hook: what it does and at which point it fires), when the change takes effect, the resolved runtime and whether each value was user-specified or inherited, and validation results. For an agent that a program uses, also report the way chosen and, on the API path, the owner's steps, the Agent ID and the Base URL.
## The embedded agent of an SDK app
-An app built with the penguin-sdk skill carries its own agent inside the project (`createAgent({ root })` initializes `<app>/penguin_data/default_project/agents/default_agent/` on first run). That directory has exactly the layout described here, and everything in this skill applies to it: write the app's persona into its `agent_state/AGENTS.md` (the penguin-sdk recipe keeps the source of truth in the project's `persona.md` and copies it in during ingest), and set `name`/`description` in its `system_config.yaml` so the app is recognizable. This is how "the app becomes an expert on X": the persona lives in the embedded agent's AGENTS.md, not in application code.
+On the SDK path, an app built with the penguin-sdk skill carries its own agent inside the project (`createAgent({ root })` initializes `<app>/penguin_data/default_project/agents/default_agent/` on first run). That directory has exactly the layout described here, and everything in this skill applies to it: write the app's persona into its `agent_state/AGENTS.md` (the penguin-sdk recipe keeps the source of truth in the project's `persona.md` and copies it in during ingest), and set `name`/`description` in its `system_config.yaml` so the app is recognizable. This is how "the app becomes an expert on X": the persona lives in the embedded agent's AGENTS.md, not in application code.
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9db5cad9..b3fbb6fe 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -46,6 +46,18 @@ importers:
specifier: ^3.2.6
+ packages/amsp:
+ devDependencies:
+ tsup:
+ specifier: ^8.3.0
+ typescript:
+ specifier: ^5.6.0
+ version: 5.9.3
+ vitest:
+ specifier: ^3.2.6
+
packages/cli:
dependencies:
'@lmliheng/agent-company':
@@ -416,6 +428,9 @@ importers:
'@larksuiteoapi/node-sdk':
specifier: ^1.73.0
+ '@lmliheng/amsp':
+ specifier: workspace:*
+ version: link:../amsp
'@lmliheng/penguin-core':
specifier: workspace:*
version: file:packages/core([email protected])([email protected])
@@ -614,6 +629,9 @@ importers:
packages/web:
dependencies:
+ '@lmliheng/amsp':
+ specifier: workspace:*
+ version: link:../amsp
'@lmliheng/penguin-core':
specifier: workspace:*
version: file:packages/core([email protected])([email protected])
@@ -1495,6 +1513,10 @@ packages:
'@lmliheng/agent-tuning@file:plugins/agent-tuning':
resolution: {directory: plugins/agent-tuning, type: directory}
+ '@lmliheng/amsp@file:packages/amsp':
+ resolution: {directory: packages/amsp, type: directory}
+ engines: {node: '>=24'}
+
'@lmliheng/browser-automation@file:plugins/browser-automation':
resolution: {directory: plugins/browser-automation, type: directory}
@@ -5590,6 +5612,8 @@ snapshots:
'@lmliheng/agent-tuning@file:plugins/agent-tuning': {}
+ '@lmliheng/amsp@file:packages/amsp': {}
+
'@lmliheng/browser-automation@file:plugins/browser-automation': {}
'@lmliheng/continual-learning@file:plugins/continual-learning': {}
@@ -5730,6 +5754,7 @@ snapshots:
dependencies:
'@hono/node-server': 2.0.12([email protected])
'@larksuiteoapi/node-sdk': 1.73.0([email protected]([email protected]))([email protected])
+ '@lmliheng/amsp': file:packages/amsp
'@lmliheng/penguin-core': file:packages/core([email protected])([email protected])
'@xterm/headless': 5.5.0
dotenv: 17.4.2
@@ -5757,6 +5782,7 @@ snapshots:
dependencies:
'@hono/node-server': 2.0.12([email protected])
'@larksuiteoapi/node-sdk': 1.73.0([email protected]([email protected]))([email protected])
+ '@lmliheng/amsp': file:packages/amsp
'@lmliheng/penguin-core': file:packages/core([email protected])([email protected])([email protected])
'@xterm/headless': 5.5.0
dotenv: 17.4.2