From 01622abde7f19c2bf6cc1f1a3c772ff6f55e2fb8 Mon Sep 17 00:00:00 2001
From: Tianyi Cui <53024+tianyicui@users.noreply.github.com>
Date: Wed, 22 Jul 2026 22:58:05 +0800
Subject: [PATCH] docs(i18n): refresh core data translations after merge
---
.agents/notes/README.i18n.yaml | 4 +-
.agents/notes/README.zh.md | 46 +-
docs/core-data-structures/approval.i18n.yaml | 4 +-
docs/core-data-structures/approval.zh.md | 26 +-
docs/core-data-structures/bash.i18n.yaml | 4 +-
docs/core-data-structures/bash.zh.md | 236 +++--
.../code-runtime.i18n.yaml | 4 +-
docs/core-data-structures/code-runtime.zh.md | 38 +-
.../core-data-structures/compaction.i18n.yaml | 4 +-
docs/core-data-structures/compaction.zh.md | 52 +-
docs/core-data-structures/core.i18n.yaml | 4 +-
docs/core-data-structures/core.zh.md | 335 ++++---
.../core-data-structures/filesystem.i18n.yaml | 4 +-
docs/core-data-structures/filesystem.zh.md | 114 ++-
.../llm-streaming.i18n.yaml | 4 +-
docs/core-data-structures/llm-streaming.zh.md | 152 ++-
.../persistence.i18n.yaml | 4 +-
docs/core-data-structures/persistence.zh.md | 66 +-
docs/core-data-structures/sandbox.i18n.yaml | 4 +-
docs/core-data-structures/sandbox.zh.md | 71 +-
docs/core-data-structures/scope.i18n.yaml | 4 +-
docs/core-data-structures/scope.zh.md | 30 +-
.../session-query.i18n.yaml | 4 +-
docs/core-data-structures/session-query.zh.md | 109 ++-
docs/core-data-structures/session.i18n.yaml | 4 +-
docs/core-data-structures/session.zh.md | 407 ++++++--
docs/core-data-structures/skills.i18n.yaml | 4 +-
docs/core-data-structures/skills.zh.md | 47 +-
docs/core-data-structures/subagent.i18n.yaml | 4 +-
docs/core-data-structures/subagent.zh.md | 155 +++-
.../system-prompt.i18n.yaml | 4 +-
docs/core-data-structures/system-prompt.zh.md | 24 +-
docs/core-data-structures/tools.i18n.yaml | 4 +-
docs/core-data-structures/tools.zh.md | 182 +++-
.../user-interaction.i18n.yaml | 4 +-
.../user-interaction.zh.md | 15 +-
docs/core-data-structures/web.i18n.yaml | 4 +-
docs/core-data-structures/web.zh.md | 53 +-
docs/core-data-structures/workflow.i18n.yaml | 4 +-
docs/core-data-structures/workflow.zh.md | 65 +-
...-acp-default-export-drops-inject.i18n.yaml | 4 +-
...0001-acp-default-export-drops-inject.zh.md | 2 +-
...ession-disabled-filesystem-tools.i18n.yaml | 4 +-
...expression-disabled-filesystem-tools.zh.md | 8 +-
docs/postmortem/README.i18n.yaml | 4 +-
docs/postmortem/README.zh.md | 2 +-
scripts/type-equiv.manifest.json | 867 +++++++++++++++++-
47 files changed, 2685 insertions(+), 509 deletions(-)
diff --git a/.agents/notes/README.i18n.yaml b/.agents/notes/README.i18n.yaml
index 680bf965c7..7344c11eec 100644
--- a/.agents/notes/README.i18n.yaml
+++ b/.agents/notes/README.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-README.md: 9014579f3a98be907885332a0c815bca5c96855c
-README.zh.md: 3ed8b5a03c7f5888a331d0220a7b7c7fb6cd68e2
+README.md: 4db9f16956b9c569cf5f9b53f04cb650f6058668
+README.zh.md: b98d54ca64ed6150ddfc9f25c98ac64fe9a344f0
diff --git a/.agents/notes/README.zh.md b/.agents/notes/README.zh.md
index 3ed8b5a03c..b98d54ca64 100644
--- a/.agents/notes/README.zh.md
+++ b/.agents/notes/README.zh.md
@@ -1,32 +1,34 @@
-# RFC
+# Agent Notes
[English](README.md) | 中文
-这里存放一类设计文档。**RFC** 记录塑造本代码库的决策或提案:代码和文档无法承载的*为什么*以及*放弃了什么*。完整列表见生成的 [INDEX.md](INDEX.md);本文件是契约:RFC 存放在哪里、何时需要写一份,以及[文件内格式](#the-file-format)。
+这里存放一类设计文档。**Agent Note(agent 决策记录)** 记录塑造本代码库的决策或提案:代码和文档无法承载的*为什么*以及*放弃了什么*。本文件是入口和契约:Agent Note 存放在哪里、何时需要写一份,以及[文件内格式](#the-file-format)。
## 布局与命名
-每份 RFC 有两个维度,都编码在其**路径**中:`{lifecycle}/{class}/yyyy-mm-dd-topic-title.md`。
+每份 Agent Note 有两个维度,都编码在其**路径**中:`{lifecycle}/{class}/yyyy-mm-dd-topic-title.md`。
-- **生命周期**(顶层文件夹)是 RFC 的状态,RFC 随状态变化在文件夹之间移动:
+- **生命周期**(顶层文件夹)是 Agent Note 的状态,Agent Note 随状态变化在文件夹之间移动:
- **`proposed/`**:实施前评审的提案;尚未构建(或仅部分构建)。
- - **`implemented/`**:决策已交付。文件记录做了什么决定、否决了什么,并**与实际交付的内容保持同步**:当代码后续移动文件、重命名包(package)或更改键名/默认值时,RFC 在同一个变更中同步更新(仅限事实——路径、名称、结构——而非决策本身)。见 [implemented/AGENTS.md](implemented/AGENTS.md)。
+ - **`implemented/`**:决策已交付。文件记录做了什么决定、否决了什么,并**与实际交付的内容保持同步**:当代码后续移动文件、重命名包(package)或更改键名/默认值时,Agent Note 在同一个变更中同步更新(仅限事实——路径、名称、结构——而非决策本身)。见 [implemented/AGENTS.md](implemented/AGENTS.md)。
- **`rejected/`**:提案经过讨论后被否决。保留以备查阅,避免同一问题被反复争论。
- **类别**(嵌套文件夹)是决策的*种类*——见下方[分类](#classification)。
-文件名中的日期是该主题**首次提出**的时间(以 git 历史为准)。RFC 之间的交叉引用使用相对 Markdown 链接(`[topic](../../implemented/architecture/2026-…-….md)`),从不使用纯文字或编号,这样既可机械检查,也能在文件夹间移动时保持有效。
+文件名中的日期是该主题**首次提出**的时间(以 git 历史为准)。Agent Note 之间的交叉引用使用相对 Markdown 链接(`[topic](../../implemented/architecture/2026-…-….md)`),从不使用纯文字或编号,这样既可机械检查,也能在文件夹间移动时保持有效。
+
+目录树就是清单:浏览其生命周期/类别文件夹,或搜索仓库即可。请勿添加集中式 `INDEX.md`;设计理由见[不设索引的 Agent Note](implemented/process/2026-07-19-remove-generated-agent-note-index.md)。
## 分类
-每份 RFC 属于 `scripts/rfc-index.ts` 中封闭集合里的一个路径编码类别;分类门禁拒绝其他文件夹。[INDEX.md](INDEX.md) 由路径、标题和文件名日期生成,其新鲜度受门禁保护。新增类别需要同时更新规范集合与本节。见[分类 RFC](implemented/process/2026-06-20-rfc-classification.md) 与[索引生成 RFC](implemented/process/2026-07-04-generate-rfc-index-tables.md)。
+每份 Agent Note 属于 `scripts/agent-note-tree.ts` 中封闭集合里的一个路径编码类别;分类门禁拒绝其他文件夹。新增类别需要同时更新规范集合与本节。见[分类 Agent Note](implemented/process/2026-06-20-agent-note-classification.md)。
| 类别 | 覆盖范围 |
|---|---|
-| `feature` | 面向用户或模型的新能力。 |
+| `feature` | 面向用户或模型的新功能。 |
| `bug-fix` | 修正缺陷或弥补事故复盘(postmortem)发现的缺口。 |
-| `simplification` | 在不增加能力的前提下移除代码、行为或对外表面积。 |
+| `simplification` | 在不增加功能的前提下移除代码、行为或对外表面积。 |
| `architecture` | 关于**交付源码**的结构性决策:包之间的关系、运行时词汇。 |
| `process` | 代码**周边**的工具、策略或工作流——门禁、包管理器、vendor 化——不涉及运行时行为。 |
| `testing` | 测试基础设施与策略。 |
@@ -35,22 +37,22 @@
## 何时需要写一份
-当一个决策具备以下三个特征时,请写一份 RFC:**持久性**(它的影响超出单个函数或包)、**争议性**(存在一个合理工程师可能选择的真实替代方案)、**意外性**(未来读者否则会问「为什么要这样做」)。对未来重大工作的提案从 `proposed/` 开始;已经做出的决策从 `implemented/` 开始。选择与决策匹配的类别文件夹(见[分类](#classification))。
+每个非平凡变更都必须在同一 PR 中新增或更新至少一份 Agent Note。如果变更修改了行为、架构、跨文件或跨包契约、流程或工具、测试策略、磁盘、协议或配置格式,或者其他维护者可能合理重新审视的决策,就属于非平凡变更。对未来重大工作的提案从 `proposed/` 开始;已经做出的决策从 `implemented/` 开始。选择与决策匹配的类别文件夹(见[分类](#classification))。
-以下情况不要写 RFC:机械性或局部的选择(一个变量名、一次单文件重构);已由门禁或 AGENTS.md 中的约定强制执行并解释的事项;代码中标记为 `TODO(...)` 的临时决策——将其记为 TODO,待稳定后再升级为 RFC。RFC 永远不会被编辑为一个*不同的决策*:用新 RFC 取代旧的,并互相链接。(编辑 `implemented/` RFC 以跟踪其已做出的决策现在*位于*何处——移动的文件、重命名的包——不是不同的决策,这是必需的而非禁止的;见 [implemented/AGENTS.md](implemented/AGENTS.md)。)
+更新已经拥有该决策的 Agent Note 即可满足规则;不要创建重复记录。只有不涉及行为、契约、结构、流程或理由变化的纯机械性或局部编辑才可豁免。Agent Note 永远不会被编辑为一个*不同的决策*:用新 Agent Note 取代旧的,并互相链接。编辑 `implemented/` Agent Note 以跟踪其现有决策的所在位置是必需的,而非禁止的;见 [implemented/AGENTS.md](implemented/AGENTS.md)。
## 文件格式
-每份 RFC 遵循统一的文件内格式,由 `pnpm run verify-rfc-format`([scripts/verify-rfc-format.ts](../../scripts/verify-rfc-format.ts),`doc-sync`(文档同步门禁)的一环)强制执行;该格式的设计动机及其否决的替代方案见[统一格式 RFC](implemented/process/2026-07-05-uniform-rfc-format.md)。
+每份 Agent Note 遵循统一的文件内格式,由 `pnpm run verify-agent-note-format`([scripts/verify-agent-note-format.ts](../../scripts/verify-agent-note-format.ts),`doc-sync`(文档同步门禁)的一环)强制执行;该格式的设计动机及其否决的替代方案见[统一格式 Agent Note](implemented/process/2026-07-05-uniform-agent-note-format.md)。
### 头部块
-每份 RFC 的前三行严格为:
+每份 Agent Note 的前三行严格为:
```markdown
-# RFC:
+# Agent Note:
Status:
```
@@ -61,11 +63,11 @@ Status:
- `Status: implemented`
- `Status: rejected — `
-状态行不带日期、不带括号补充说明:文件名记录首次提出日期,git 记录其余一切;「以修订形式接受」之类的说明属于正文内容(在陈述决策的地方说明修订)。拒绝原因是唯一带内容的状态,因为读者查阅被否决的 RFC 时,结论正是他们要找的。
+状态行不带日期、不带括号补充说明:文件名记录首次提出日期,git 记录其余一切;「以修订形式接受」之类的说明属于正文内容(在陈述决策的地方说明修订)。拒绝原因是唯一带内容的状态,因为读者查阅被否决的 Agent Note 时,结论正是他们要找的。
### 正文骨架
-每份 RFC 的正文以 `## Problem` 开头:动机,写法上不依赖解决方案即可独立成文。后续内容取决于生命周期;固定章节使用以下规范名称且仅限这些名称,而真正独特的技术章节(包拓扑、协议契约、schema 等)在必需章节之间可自由组织。
+每份 Agent Note 的正文以 `## Problem` 开头:动机,写法上不依赖解决方案即可独立成文。后续内容取决于生命周期;固定章节使用以下规范名称且仅限这些名称,而真正独特的技术章节(包拓扑、协议契约、schema 等)在必需章节之间可自由组织。
#### `proposed/`
@@ -90,20 +92,20 @@ Status:
## Consequences
```
-`## Decision` 以现在时态描述已交付的现实,整个文件按 [implemented/AGENTS.md](implemented/AGENTS.md) 的要求与之保持同步。`## Consequences` 记录权衡的代价**与**收益。提案阶段的标题在此属于规格用语,门禁会拒绝它们:`## Proposal`、`## Plan`、`## Migration plan` 和 `## Acceptance criteria` 不得出现在 implemented RFC 中(原因见 [slop 检查清单](../AGENTS.md))。`## Testing`、`## Deferred` 或 `## Related` 章节在陈述现在时态的事实时是允许的。
+`## Decision` 以现在时态描述已交付的现实,整个文件按 [implemented/AGENTS.md](implemented/AGENTS.md) 的要求与之保持同步。`## Consequences` 记录权衡的代价**与**收益。提案阶段的标题在此属于规格用语,门禁会拒绝它们:`## Proposal`、`## Plan`、`## Migration plan` 和 `## Acceptance criteria` 不得出现在 implemented Agent Note 中(原因见 [slop 检查清单](../../docs/AGENTS.md))。`## Testing`、`## Deferred` 或 `## Related` 章节在陈述现在时态的事实时是允许的。
#### `rejected/`
-被否决的 RFC 是冻结的提案:保留提案时的所有章节(包括 `## Acceptance criteria` 或 `## Plan`),结论写在 `Status:` 行上。仅头部块、`## Problem` 开头、`## Proposal` 章节以及下方的「曾考虑的替代方案」强制要求适用。
+被否决的 Agent Note 是冻结的提案:保留提案时的所有章节(包括 `## Acceptance criteria` 或 `## Plan`),结论写在 `Status:` 行上。仅头部块、`## Problem` 开头、`## Proposal` 章节以及下方的「曾考虑的替代方案」强制要求适用。
### 曾考虑的替代方案——必需
-每份 RFC 都必须包含 `## Alternatives considered` 章节:每个真实的替代方案及其落选原因,每个替代方案用一个加粗引导的段落,或对争议较大的替代方案用 `### Why not ?` 子节。记录决策时不记录它击败了什么,就是在邀请反复争论——正是 RFC 存在的意义所要防止的。
+每份 Agent Note 都必须包含 `## Alternatives considered` 章节:每个真实的替代方案及其落选原因,每个替代方案用一个加粗引导的段落,或对争议较大的替代方案用 `### Why not ?` 子节。记录决策时不记录它击败了什么,就是在邀请反复争论——正是这些 Agent Note 存在的意义所要防止的。
-替代方案是记录下来的,不是凭空编造的。日期早于 2026-07-05 且替代方案无法从记录中重建的 RFC,在该章节位置放置以下精确注释,门禁仅对格式规范之前的文件接受此注释:
+替代方案是记录下来的,不是凭空编造的。日期早于 2026-07-05 且替代方案无法从记录中重建的 Agent Note,在该章节位置放置以下精确注释,门禁仅对格式规范之前的文件接受此注释:
```markdown
-
+
```
### 在生命周期之间移动
@@ -112,4 +114,4 @@ Status:
### 中文对侧文件
-`.zh.md` 对侧文件按 [i18n 契约](../i18n/README.md)逐章节镜像其英文兄弟文件的结构;机器检查的头部标记(`# RFC: ` 和 `Status:` 行)保持英文原样不翻译。格式门禁跳过 `.zh.md` 文件——配对门禁负责它们的一致性。
+`.zh.md` 对侧文件按 [i18n 契约](../../docs/i18n/README.md)逐章节镜像其英文兄弟文件的结构;机器检查的头部标记(`# Agent Note: ` 和 `Status:` 行)保持英文原样不翻译。格式门禁跳过 `.zh.md` 文件——配对门禁负责它们的一致性。
diff --git a/docs/core-data-structures/approval.i18n.yaml b/docs/core-data-structures/approval.i18n.yaml
index 9a644ee85a..c6bfeafaf9 100644
--- a/docs/core-data-structures/approval.i18n.yaml
+++ b/docs/core-data-structures/approval.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-approval.md: 772582955145092f3d483c297f7704b2b8506375
-approval.zh.md: 706613b84784d81cf112622059c755e815c23f16
+approval.md: c9b411e38508fc7e8ac2e2dd923d9c8cc2f475a3
+approval.zh.md: ee593298fece8b2782228f2e93c5509871e15166
diff --git a/docs/core-data-structures/approval.zh.md b/docs/core-data-structures/approval.zh.md
index 706613b847..ee593298fe 100644
--- a/docs/core-data-structures/approval.zh.md
+++ b/docs/core-data-structures/approval.zh.md
@@ -8,15 +8,23 @@
## 标识与结果
-每个请求获得一个全新的 `ApprovalRequestId`。该品牌类型将 `approval/asked` 和 `approval/decided` 审计事件配对,同时确保审批 id 不会与 tool-call、session 或 agent id 混用。
+每个请求都会获得一个全新的 `ApprovalRequestId`。该品牌类型将 `approval/asked` 与 `approval/decided` 审计事件配对,同时不会让审批 id 与工具调用 id 或 agent/session id 互换。
```ts type-equiv
+/**
+ * Pairs one `approval/asked` audit event with its `approval/decided`.
+ * Service-issued (one fresh id per {@link ApprovalService.request} call).
+ */
type ApprovalRequestId = Branded<'ApprovalRequestId'>
```
`ApprovalOutcome` 是闭合的,且默认拒绝。`allowed-once` 仅授权所询问的那一个操作;调用方对 `rejected`、`cancelled` 和 `unavailable` 均执行拒绝。缺失、无所有权、抛异常或不合规的应答者会产生 `unavailable`,而非放行。
```ts type-equiv
+/**
+ * Closed approval outcomes: a one-shot grant, explicit rejection, withdrawn
+ * request, or unavailable answerer. Callers fail closed on `unavailable`.
+ */
type ApprovalOutcome = 'allowed-once' | 'rejected' | 'cancelled' | 'unavailable'
```
@@ -25,6 +33,18 @@ type ApprovalOutcome = 'allowed-once' | 'rejected' | 'cancelled' | 'unavailable'
`ApprovalPolicy` 决定在交互式应答者运行之前发生什么。`ask` 委托给组合的应答者链,链的无应答默认值为 `unavailable`;`never` 确定性地返回 `rejected`,不分发任何应答者。生效值为会话日志中最后一条 `approval/policy` 事件,回退到服务配置。`setApprovalPolicy(session, policy)` 是唯一的写入路径,因此回放能重建覆盖值。
```ts type-equiv
+/**
+ * A session's approval policy — what happens to an {@link ApprovalService}
+ * ask BEFORE any interactive answerer sees it:
+ *
+ * - `'ask'` (the default) — delegate to the composed answerers; with none
+ * composed the chain falls through to the fail-closed `'unavailable'`
+ * (exactly today's behavior).
+ * - `'never'` — never prompt anyone: every ask resolves `'rejected'`
+ * deterministically. The strict headless stance (CI, unattended runs) and
+ * the only policy value stated in the system prompt — unlike `'ask'`, its
+ * outcome is knowable without asking, so stating it cannot overclaim.
+ */
type ApprovalPolicy = 'ask' | 'never'
```
@@ -35,6 +55,10 @@ type ApprovalPolicy = 'ask' | 'never'
`ApprovalRequest` 以足够精确的方式标识 agent 和工具操作,以便路由和审计该问题。它有意省略工具参数:应答者通过 `callId` 将提示附加到已流式输出的工具调用上,而非渲染一份可能漂移的副本。
```ts type-equiv
+/**
+ * Readonly same-process permission question. `callId` links to an already
+ * presented tool call, so arguments are not duplicated here.
+ */
interface ApprovalRequest {
/**
* The agent on whose behalf the question is asked. Routes the question (a
diff --git a/docs/core-data-structures/bash.i18n.yaml b/docs/core-data-structures/bash.i18n.yaml
index 601c350359..168c96a10a 100644
--- a/docs/core-data-structures/bash.i18n.yaml
+++ b/docs/core-data-structures/bash.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-bash.md: 7b5c779b832ef5be6591e626980f7f22db54f239
-bash.zh.md: c4d27efa8344727e3a77c928b331ec570c2716eb
+bash.md: 35cf2061588907dde41123efb01e453eb9cc929d
+bash.zh.md: 56e5ae7b6231575a6b591093724d5560ade27056
diff --git a/docs/core-data-structures/bash.zh.md b/docs/core-data-structures/bash.zh.md
index c4d27efa83..56e5ae7b62 100644
--- a/docs/core-data-structures/bash.zh.md
+++ b/docs/core-data-structures/bash.zh.md
@@ -2,21 +2,48 @@
[English](bash.md) | 中文
-Bash 执行 seam:典型的[能力 seam](../rfc/implemented/architecture/2026-06-13-capability-seams.md) 示例,拆分为三个包(package):接口([dsh-bash](../../packages/bash/bash),`ctx.bash`)、实现([dsh-bash-local](../../packages/bash/bash-local),本地子进程)和消费方([dsh-tool-bash](../../packages/bash/tool-bash),`bash`/`bash_output`/`bash_kill` 工具 schema)。Bash 是**一项可选能力**,不属于 agent loop(智能体循环)主干,因此其词汇定义在此处而非 [core.md](core.md)。沙箱化、容器化或远程后端是实现同一接口的兄弟包。
+bash 执行 seam 分为接口([dsh-bash](../../packages/bash/bash),`ctx.bash`)、实现([dsh-bash-local](../../packages/bash/bash-local) 与 [dsh-bash-sandbox](../../packages/bash/bash-sandbox))和消费方([dsh-tool-bash](../../packages/bash/tool-bash),即 `bash` schema)。通用后台任务的 id、所有权与控制位于 [tasks.md](tasks.md);本 seam 返回一个不含任务概念的进程句柄。
源码:[`packages/bash/bash/src/types.ts`](../../packages/bash/bash/src/types.ts)
-## 请求与规格:`resolve()` 拆分
+## 受管 shell 环境命名空间
-该 seam 将**面向模型/插件的请求**(`workdir`/`timeoutMs` 可选,由配置填充)与**执行器实际执行的完全解析规格**(这些字段为必填)分离。工具层在二者之间调用 `ctx.bash.resolve(request)`。这是本仓库「在包边界处显式优于隐式」规则的具体体现:阅读 `BashExecSpec` 的人永远不会疑惑工作目录从何而来。
+`DSH_*` 变量是归 Harness 所有的子进程事实。面向模型的 bash 工具通过 `ctx.bashEnv` 收集它们,再经由 `BashExecRequest.dshEnv` 传递;执行器在合并当前快照之前会移除继承而来的 `DSH_*` 名称。
```ts type-equiv
+/** One environment key inside the managed {@link DSH_ENV_PREFIX} namespace. */
+type DshEnvironmentKey = `${typeof DSH_ENV_PREFIX}${string}`
+```
+
+```ts type-equiv
+/** Trusted DeepSeek Harness variables for one bash execution. */
+type DshEnvironment = Readonly>
+```
+
+## 请求与规格:`resolve()` 拆分
+
+该 seam 将**面向模型/插件的请求**(`workdir`/`timeoutMs`/`stdoutMaxBytes` 可选,由配置或请求策略补全)与执行器实际使用的**完全解析后的 spec**(这些字段均为必填)分开。工具层在二者之间调用 `ctx.bash.resolve(request)`——这具体落实了仓库的「包 seam 上显式优于隐式」规则:`BashExecSpec` 的读者不必猜测工作目录或输出预算来自何处。
+
+```ts type-equiv
+/**
+ * A caller's execution REQUEST: `workdir` and `timeoutMs` are optional and
+ * filled by {@link BashExecutor.resolve} from the implementation's config.
+ * This is the model-/plugin-facing shape; pass it to `resolve()` to obtain a
+ * fully-resolved {@link BashExecSpec}.
+ */
interface BashExecRequest {
command: string
/** Working directory override (default: implementation-configured). */
workdir?: string | undefined
/** Timeout override in milliseconds (implementations cap it). */
timeoutMs?: number | undefined
+ /**
+ * Foreground stdout capture budget in bytes. Absent uses the executor's
+ * default output cap. Trusted in-process consumers use this when they must
+ * parse complete stdout up to their own bounded limit; the model-facing bash
+ * tool does not expose it as a parameter.
+ */
+ stdoutMaxBytes?: number | undefined
/** Abort signal — implementations kill the command when it fires. */
signal?: AbortSignal | undefined
/**
@@ -28,115 +55,92 @@ interface BashExecRequest {
*/
stdin?: string | undefined
/**
- * Extra environment entries for the command, merged AFTER the
- * implementation's credential scrub (so an explicit entry here is honored even
- * when its name matches the scrub pattern — the caller named a value it holds,
- * not the harness's ambient secret). Set by in-process plugins (the hooks
- * bridges set `CLAUDE_PROJECT_DIR`, `CLAUDE_PLUGIN_ROOT`, …); the model-facing
- * bash tool does not expose it as a parameter (a model that needs an env var
- * uses shell syntax like `FOO=bar cmd`).
+ * Ordinary environment entries for the command, merged after the credential
+ * scrub. `DSH_*` is reserved for {@link dshEnv} and implementations reject it
+ * here. Set by in-process plugins (the hooks bridges set
+ * `CLAUDE_PROJECT_DIR`, `CLAUDE_PLUGIN_ROOT`, …); the model-facing bash tool
+ * does not expose it as a parameter.
*/
env?: Record | undefined
/**
- * Opaque OWNER token for a background task — the consumer's isolation key
- * (the tool layer passes the owning agent's `session.header.id`). The
- * executor stores it on the task and exposes it via {@link BashExecutor.ownerOf};
- * the executor itself NEVER interprets it (no access policy lives in the
- * seam — that is the consumer's job). Absent for foreground runs and for an
- * ownerless background start (a non-agent caller).
+ * Harness-owned `DSH_*` variables for this execution. Executors discard
+ * ambient `DSH_*` entries before merging this snapshot, so an unavailable
+ * current fact cannot inherit a stale value from the harness process, and
+ * reject non-`DSH_*` names supplied through this managed channel.
*/
- owner?: OwnerToken | undefined
- /**
- * Explicit per-call sandbox-policy input, overriding the executor's
- * configured default mode for THIS call. Never a silent default: a
- * consumer sets it only from an explicit policy source — an
- * `'allowed-once'` grant a human just issued through `ctx.approval` (the
- * escalation flow in the sandbox RFC § Escalation, which outranks), or the
- * session's standing override folded from its own `bash/sandbox-mode`
- * events (the sandbox RFC § Per-session mode switching — the user's recorded per-session
- * choice). A sandboxing executor confines THIS call under the given mode;
- * a non-sandboxing executor carries the field and confines nothing (the
- * tool layer stamps neither escalation nor overrides without a sandboxing
- * executor — see {@link BashExecutor.sandboxMode}).
- */
- sandboxMode?: SandboxMode | undefined
+ dshEnv?: DshEnvironment | undefined
+ /** Fully resolved per-call sandbox policy; sandboxing executors default it. */
+ sandboxPolicy?: SandboxExecutionPolicy | undefined
}
```
```ts type-equiv
+/**
+ * A resolved execution spec. {@link BashExecutor.resolve} fills and caps the
+ * required fields; {@link BashExecutor.start} ignores `timeoutMs` because
+ * background processes have no executor timeout.
+ */
interface BashExecSpec {
command: string
workdir: string
timeoutMs: number
+ /**
+ * Resolved foreground stdout capture budget in bytes. `run()` uses it for
+ * stdout; background tasks and stderr keep the executor's own output cap.
+ */
+ stdoutMaxBytes: number
/** Abort signal — implementations kill the command when it fires. */
signal?: AbortSignal | undefined
- /**
- * Bytes to write to the command's stdin (then close it), carried through
- * verbatim from {@link BashExecRequest.stdin}. OPTIONAL on the resolved spec
- * (unlike `owner`): it has no config default, so a missing one means "no
- * stdin" — the safe, ordinary case — not a silent footgun, so it stays a
- * plain optional rather than required-but-nullable (see the request field).
- */
+ /** Bytes to write to stdin before closing it; absent means no stdin. */
stdin?: string | undefined
/**
- * Extra environment entries, carried through verbatim from
- * {@link BashExecRequest.env} and merged by the implementation AFTER its
- * credential scrub (an explicit entry wins even when its name matches the
- * scrub pattern). OPTIONAL on the spec for the same reason as `stdin` — no
- * config default, absent means "no extra env".
+ * Ordinary environment entries carried through from
+ * {@link BashExecRequest.env}. `DSH_*` remains reserved for {@link dshEnv}.
+ * OPTIONAL on the spec for the same reason as `stdin`: absent means no
+ * ordinary extra environment.
*/
env?: Record | undefined
- /**
- * Opaque owner token, REQUIRED-but-nullable (mirrors `workdir`/`timeoutMs`
- * being required on the resolved spec): {@link BashExecutor.resolve} carries
- * the request's `owner` through, defaulting a missing one to `undefined`. A
- * required field makes a forgotten owner a VISIBLE `undefined` rather than a
- * silently-absent property that yields an unowned (cross-session-readable)
- * task. `start()` stores it; `run()` (foreground) ignores it.
- */
- owner: OwnerToken | undefined
- /**
- * The sandbox mode this call executes under, REQUIRED-but-nullable for the
- * same visibility reason as `owner`. A sandboxing executor's `resolve()`
- * stamps the effective mode (the request's explicit override, else its
- * configured default) so `run()`/`start()` read the spec, never the config;
- * a non-sandboxing executor carries the request value through verbatim and
- * ignores it (`undefined` under such an executor means what its README says:
- * unconfined execution).
- */
- sandboxMode: SandboxMode | undefined
+ /** Managed `DSH_*` snapshot; implementations reject ordinary names. */
+ dshEnv?: DshEnvironment | undefined
+ /** Resolved sandbox policy; ignored by executors that do not confine. */
+ sandboxPolicy: SandboxExecutionPolicy | undefined
}
```
-`owner` token 是隔离键:执行器存储它但从不解释它(访问策略是消费方的职责),因此一个 agent 启动的后台任务不会被跨会话读取。必填但可空的字段使遗忘的 owner 成为一个可见的 `undefined`,而非一个静默无主的任务。
+`stdin` 和 `env` 是受信任的进程内插件输入,不由 `dsh-tool-bash` 暴露。本地执行器会先清除环境中的凭据,再合并调用方显式提供的 env。见 [bash-stdin-env Agent Note(agent 决策记录)](../../.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.md)。
-受信的进程内插件使用 `stdin` 和 `env` 传递钩子载荷与钩子专用变量。面向模型的 bash 工具从其命名的 schema 字段构造请求,不暴露这两个输入,因为 shell 语法本身已提供等价能力;测试防止未来出现 `...args` 展开。这是请求形状的纪律约束,而非安全边界:`dsh-bash-local` 无论这些字段如何都会清洗环境凭证,然后叠加调用方已持有的显式值。见 [bash stdin/env RFC](../rfc/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.md)。
-
-该 seam 处理的两个 id 都是[品牌化的](core.md)(零成本 `string` 品牌,与 `SessionId`/`AgentId` 相同的机制):`BashTaskId`(被跟踪的后台任务,由本地执行器生成 `bash-N`)和 `OwnerToken`(不透明的隔离键)。`OwnerToken` 刻意是一个与 `SessionId` 不同的品牌,而非别名:bash seam 是一个能力 seam,不得知道 owner token *意味着*什么,因此它从不导入 `dsh-session` 的词汇。`dsh-tool-bash` 消费方是唯一将拥有者 agent 的 `SessionId` 转换为 `OwnerToken` 的边界。对两者施加品牌化,可以防止裸 `string`(或在需要 `OwnerToken` 的地方传入 `BashTaskId`,反之亦然)在面向模型的 `task_id` 路径上通过类型检查。
+`stdoutMaxBytes` 同样仅供受信任插件使用。它让前台消费方能在有界解析预算内请求完整 stdout,而不会改变 stderr、后台任务或面向模型的 bash 工具的常规输出上限。
## 前台运行:`BashRunResult`
一次已完成(或被终止)的前台运行的结果。正交的结果**独立报告**:一个进程可以同时超时并以退出码 0 退出(因为它捕获了信号),因此 `timedOut`、`aborted`、`signal` 和 `exitCode` 各自独立为一个字段;调用方永远不会把一次被截断的运行误读为干净的成功。
```ts type-equiv
+/** The outcome of one completed (or killed) foreground run. */
interface BashRunResult {
/** Exit code; null when the process died from a signal. */
exitCode: number | null
/** Terminating signal (e.g. 'SIGTERM'); null on normal exit. */
signal: NodeJS.Signals | null
- /** True when the executor's own timeout killed the command. */
+ /**
+ * True when the executor's own timeout was the FIRST cause to cut the command
+ * short. Mutually exclusive with {@link aborted}: one fused deadline drives
+ * both the timeout and the caller's cancellation, so a timeout and an abort
+ * racing before process close report the single first-abort cause, not both
+ * (see the [timeout-library Agent Note](../../../../.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.md)).
+ */
timedOut: boolean
- /** True when the caller's AbortSignal killed the command. */
+ /**
+ * True when the caller's `AbortSignal` was the FIRST cause to kill the command
+ * (and it was not the executor's own timeout). Mutually exclusive with
+ * {@link timedOut} — see there for the first-cause classification.
+ */
aborted: boolean
/** The effective timeout applied to this run (after defaulting/capping). */
timeoutMs: number
stdout: CollectedOutput
stderr: CollectedOutput
- /**
- * Sandbox facts, present iff a sandboxing executor ran the command — an
- * unsandboxed executor (e.g. `dsh-bash-local`) never sets it. See
- * {@link BashSandboxInfo} for the `denied` classification semantics.
- */
+ /** Sandbox execution facts, absent for an unsandboxed executor. */
sandbox?: BashSandboxInfo
}
```
@@ -144,6 +148,7 @@ interface BashRunResult {
每个流是一个 `CollectedOutput`:(可能被截断的)文本加恢复信息。截断时,`text` 是**尾部**,完整流溢出到一个私有文件:
```ts type-equiv
+/** One captured stream: the (possibly truncated) text plus recovery info. */
interface CollectedOutput {
/** Collected text — the TAIL of the stream when truncated. */
text: string
@@ -156,79 +161,70 @@ interface CollectedOutput {
## 文件沙箱:`BashSandboxInfo`
-消费沙箱的执行器(`dsh-bash-sandbox`)通过 `BashExecutor.sandboxMode` 暴露其配置的回退模式。工具层折叠每个 agent 会话的持久 `bash/sandbox-mode` 覆盖,将生效模式印到请求上,并可为一次用户批准的严格更宽调用替换它。它刻意既不声明当前模式也不叙述切换过程;拒绝结果会指明该命令实际运行时所处的模式。模式/执行词汇由 [`@deepseek-ai/dsh-sandbox` seam](sandbox.md) 拥有并编目,其提供方包装执行器的 argv;模式仅管控文件效果,不涉及网络或进程可见性。
+消费 sandbox 的执行器通过 `BashExecutor.sandboxMode` 暴露其已配置的模式回退值。工具层请求 [`@deepseek-ai/dsh-sandbox-policy`](../../packages/sandbox/sandbox-policy/README.md),把每个调用会话的持久 `sandbox/mode` 覆盖值与不可变 cwd 解析为 `BashExecRequest.sandboxPolicy`;经用户批准、严格更宽松的调用只替换模式。模式/root/enforcement 词汇归 [`@deepseek-ai/dsh-sandbox` seam](sandbox.md) 所有;模式仅管辖文件效果。
-沙箱化运行始终在 `BashRunResult.sandbox` 上报告其执行时的事实:`denied` 是执行器对失败的保守分类——判定为沙箱导致(退出失败且 stderr 携带文件系统权限特征——从不是干净退出或信号终止),从收集到的 stderr 尾部读取;`enforcement` 报告所选后端对该模式文件效果的管控完整程度(`SandboxEnforcement = 'full' | 'partial'`:`partial` 表示较旧的 Landlock ABI 仅管控所请求访问的子集;`danger-full-access` 下不存在此字段,因为没有任何限制);`runnerFailed` 标记与拒绝相反的情况——沙箱运行器本身失败、命令从未执行(仅在已结算的后台任务上标记;前台运行通过抛出 `SANDBOX_UNAVAILABLE` 错误暴露同一状况):
+sandbox 化运行会报告其模式、保守的拒绝分类与强制执行完整度。`runnerFailed` 标记命令运行前 sandbox runner 已失败;前台执行会抛出 `SANDBOX_UNAVAILABLE`,而已结束的后台进程只能通过其事实通道报告。
```ts type-equiv
+/**
+ * Sandbox facts for one run, present iff a sandboxing executor handled it.
+ * Facts are reported independently of process exit status so callers can
+ * distinguish command failures from policy denials and runner failures.
+ */
interface BashSandboxInfo {
/** The mode the command actually ran under. */
mode: SandboxMode
- /**
- * True when the executor classifies this run's failure as the sandbox
- * denying a file operation. The classification is CONSERVATIVE (a failed
- * exit whose stderr carries a filesystem-permission signature) and reads
- * the COLLECTED stderr — the bounded in-memory tail per
- * {@link CollectedOutput} semantics, so a signature that survives only in a
- * spill file is missed toward `denied: false`. A plain command failure
- * keeps `denied: false` even under a sandboxed mode.
- */
+ /** Whether the sandbox denied a file operation. */
denied: boolean
- /**
- * How completely the runner enforced `mode`'s file effects — see
- * {@link SandboxEnforcement}. Absent exactly when `mode` is
- * `danger-full-access`: nothing is confined, so there is no enforcement to
- * report.
- */
+ /** How completely the selected runner enforced the requested mode. */
enforcement?: SandboxEnforcement
- /**
- * True when the executor classifies this failure as the SANDBOX RUNNER
- * itself failing (missing binary, refused profile, fail-closed refusal
- * before exec) — the command NEVER RAN; this is a sandbox failure, not a
- * task failure, and it outranks `denied` (a runner's own error text can
- * contain denial words). Only ever stamped on settled BACKGROUND tasks: a
- * foreground run surfaces the same condition as the thrown
- * `SANDBOX_UNAVAILABLE` error instead (the foreground path has an error
- * channel; a settled task's facts are its only channel).
- */
+ /** Whether the sandbox runner failed before the command could run. */
runnerFailed?: boolean
}
```
-还有一个词汇完成整幅图景:`SANDBOX_UNAVAILABLE` 错误码(由 [sandbox seam](sandbox.md) 拥有)是 `ctx.sandbox` 提供方在受限模式没有可用后端时抛出的错误,执行器将其传播。所选运行器拒绝其 profile 时也触发同一快速失败的前台错误;已结算的后台任务则记录 `runnerFailed`。模型在结果中接收拒绝/运行器事实,仅在拒绝标记指明模式时才获知生效模式,并可通过 `sandbox_permissions` 加 `justification` 请求一次严格更宽的重试;`ctx.approval` 必须在任何执行之前批准该确切调用。完整的策略与切换设计见 [sandbox RFC](../rfc/implemented/feature/2026-07-06-sandbox.md)。
+最后一项补全了这套词汇:当受限模式没有可用后端时,`ctx.sandbox` 提供方会抛出、执行器会传播由 [sandbox seam](sandbox.md) 所有的 `SANDBOX_UNAVAILABLE` 错误码。选定的 runner 拒绝其 profile 时会触达同一个故障关闭的前台错误;已结束的后台任务则记录 `runnerFailed`。模型会在结果中收到拒绝/runner 事实,仅当拒绝标记指出生效模式时才得知该模式,并可通过 `sandbox_permissions` 加 `justification` 请求一次性、严格更宽松的重试;执行任何操作前,`ctx.approval` 必须批准该次确切调用。完整的策略与切换设计见 [sandbox Agent Note](../../.agents/notes/implemented/feature/2026-07-06-sandbox.md)。
-## 后台任务:`BashTask`
+## 后台进程:`BashProcess`
-通过 `start()` 启动的长时间运行命令被跟踪为 `BashTask`。`BashTaskStatus` 为 `'running' | 'completed' | 'killed'`;`done` 在底层进程关闭时 resolve,从不 reject。沙箱化执行器在任务结算后标记 `sandbox`(分类针对已结算任务收集到的 stderr 运行),因此该字段在运行中以及非沙箱化执行器下不存在。
+`start()` 返回不含 id 或所有者的句柄。`dsh-tool-bash` 将它适配为 `ctx.tasks.start()` hooks;随后由通用运行时拥有任务标识与生命周期。`done` 在进程关闭时 resolve 且绝不 reject;进程结束后仍可读取,并且 sandbox 事实会在 `done` resolve 前写入。
```ts type-equiv
-interface BashTask {
- readonly id: BashTaskId
- status: BashTaskStatus
+/**
+ * A background process handle returned by {@link BashExecutor.start}. It is the
+ * only access path; buffered output remains readable after exit. Executor
+ * disposal kills running processes and awaits {@link done}.
+ */
+interface BashProcess {
+ /** Process lifecycle state (settled exactly once). */
+ status: BashProcessStatus
/** Exit code once finished (null = killed by signal / still running). */
exitCode: number | null
/** Terminating signal name, when signal-killed. */
signal: NodeJS.Signals | null
- /** Resolves when the underlying process closes (never rejects). */
+ /** Resolves when the underlying process closes (never rejects — a spawn failure settles as `killed` with the error on stderr). */
readonly done: Promise
- /**
- * Sandbox facts for this task's execution, stamped by a sandboxing executor
- * once the task settles and BEFORE completion listeners are notified — an
- * `onTaskDone` consumer and a `done` awaiter both see it. Denial
- * classification runs against the settled task's collected stderr, so the
- * field cannot exist earlier: absent while the task is running and under an
- * executor that does not sandbox. See {@link BashSandboxInfo} for the
- * `denied` semantics.
- */
+ /** Sandbox facts, stamped once a confined process settles. */
sandbox?: BashSandboxInfo
+ /**
+ * Read output produced since the previous read (consuming — consecutive
+ * reads never re-deliver). Reads that lost data flag `lossy` and point at
+ * full-stream spill files when available.
+ */
+ readOutput(): BashProcessRead
+ /**
+ * Kill the process group. Returns false when it had already finished
+ * (no-op); idempotent.
+ */
+ kill(): boolean
}
```
-`readOutput()` 返回增量的 `BashTaskRead`:自上次读取以来产生的输出,附带一个 `lossy` 标志指示截断是否丢弃了未读字节:
+`readOutput()` 返回增量 delta 与 spill 恢复事实:
```ts type-equiv
-interface BashTaskRead {
- task: BashTask
+/** One incremental {@link BashProcess.readOutput} read. */
+interface BashProcessRead {
/** Output produced since the previous read (stderr in a marked section). */
delta: string
/** True when truncation dropped unread bytes the delta cannot include. */
@@ -242,4 +238,4 @@ interface BashTaskRead {
## 服务
-`BashExecutor`(`ctx.bash`,抽象——定义于 [`packages/bash/bash/src/index.ts`](../../packages/bash/bash/src/index.ts))遵循 `LlmService`/`LlmAdapter` 的拆分模式:`resolve`(请求→规格)、`run`(前台)、`start`(后台)、`get`/`ownerOf`/`list`/`readOutput`/`kill`,以及 `onTaskDone`(`BashTaskListener` 完成回调)。spawn 的命令获得一个**清洗后的 env**(丢弃 `*KEY*`/`*SECRET*`/`*TOKEN*`),溢出文件使用一个权限为 0700 的私有目录(随机文件名、仅所有者可打开)。模型输出永远不会获得环境变量或可预测路径。提供这一切的实现是 `dsh-bash-local`;调用它的面向模型的 `bash`/`bash_output`/`bash_kill` schema 位于 `dsh-tool-bash`(并通过[工具展示词汇](tools.md#tool-presentation-ui-vocabulary)作为终端呈现)。
+`BashExecutor` 拥有 `resolve`、前台 `run`、后台进程 `start` 以及 `sandboxMode` 能力事实。`dsh-bash-local` 拥有进程组、超时/中止处理、有界收集器、spill 文件、凭据清除以及 dispose 后完全停稳。`dsh-tool-bash` 拥有面向模型的渲染,并将后台句柄适配到[通用任务运行时](tasks.md)。
diff --git a/docs/core-data-structures/code-runtime.i18n.yaml b/docs/core-data-structures/code-runtime.i18n.yaml
index 918b3f5738..21bf3ee3e0 100644
--- a/docs/core-data-structures/code-runtime.i18n.yaml
+++ b/docs/core-data-structures/code-runtime.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-code-runtime.md: 28152947d0853fb10228c472ca3e121e77b7b598
-code-runtime.zh.md: 7d5750e0c245ba97ed7ece6083464382109e10fd
+code-runtime.md: a984c0f6422defc879086ff95eb94048aaa6e285
+code-runtime.zh.md: c3989fa10814139fefe91e99d9b050c1e851f8ed
diff --git a/docs/core-data-structures/code-runtime.zh.md b/docs/core-data-structures/code-runtime.zh.md
index 7d5750e0c2..c3989fa108 100644
--- a/docs/core-data-structures/code-runtime.zh.md
+++ b/docs/core-data-structures/code-runtime.zh.md
@@ -2,7 +2,7 @@
[English](code-runtime.md) | 中文
-代码执行 seam:一个[能力 seam](../rfc/implemented/architecture/2026-06-13-capability-seams.md),其接口([dsh-code-runtime](../../packages/code-runtime/code-runtime),`ctx.codeRuntime`)运行一段模型编写的程序,对接宿主提供的异步绑定,并报告程序的打印输出与返回值。代码执行是**一项可选能力**,不属于 agent loop(智能体循环)主干,因此其词汇定义在此,而非 [core.md](core.md)。后端因执行基底和源语言而异,二者都是服务上的只读描述符;worker-thread 后端与工具注册表消费方(Code Mode)在 [Code Mode RFC](../rfc/implemented/feature/2026-06-15-code-mode.md) 中定义。
+代码执行 seam 是一个[能力 seam](../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md):其接口([dsh-code-runtime](../../packages/code-runtime/code-runtime),`ctx.codeRuntime`)针对宿主提供的异步 binding 运行一段模型编写的程序,并报告其打印内容与返回值。代码执行是**一项可选能力**,不属于 agent loop 主干,因此其词汇定义在此而非 [core.md](core.md) 中。各后端的执行基底与源语言不同,这两项均为服务上的只读描述符;worker-thread 后端和工具注册表消费方(Code Mode)由 [Code Mode Agent Note(agent 决策记录)](../../.agents/notes/implemented/feature/2026-06-15-code-mode.md) 规定。
源码:[`packages/code-runtime/code-runtime/src/types.ts`](../../packages/code-runtime/code-runtime/src/types.ts)
@@ -11,6 +11,12 @@
`CodeRunRequest` 携带**运行时所需的一切**。按照「包(package)边界处显式优于隐式」的规则,默认值(时间预算、输出上限)来自实现的已校验配置,绝不是 `run()` 内部隐藏的 `??`:
```ts type-equiv
+/**
+ * One run: the program source plus everything the runtime acts on. Per the
+ * explicit-over-implicit convention, defaulting (time budgets, output caps)
+ * is the implementation's validated config — a request carries no optional
+ * tuning knobs for a hidden `??` to fill in.
+ */
interface CodeRunRequest {
/**
* The program source, in the runtime's {@link ../index.ts | language}. It
@@ -33,6 +39,11 @@ interface CodeRunRequest {
结果将错误报告为一个**字段**,而非 `run()` 的 rejection。报告失败的程序是调用方的职责,不走异常路径(与 `BashExecutor.run` 的 resolve-on-failure 契约一致):
```ts type-equiv
+/**
+ * The outcome of one run. An error is a FIELD on a resolved result, never a
+ * rejection of `run()` — reporting a failed program is the caller's job, not
+ * an exception path.
+ */
interface CodeRunResult {
/**
* The program's completion value (its top-level `return`), when it ran to
@@ -53,6 +64,13 @@ interface CodeRunResult {
每个 `CodeBindingNamespace` 在程序内成为一个由异步可调用函数组成的全局对象(Code Mode 消费方传入一个:`tools`)。参数与返回值必须可 structured-clone(运行时可能跨序列化边界桥接调用),且运行时将绑定名视为不可信输入(`__proto__` 是普通自有属性,绝不会发生原型碰撞):
```ts type-equiv
+/**
+ * A named group of {@link CodeBindingFunction}s the runtime exposes to the
+ * program as one global object (e.g. `tools`). Function names are arbitrary
+ * strings — a runtime must treat names like `__proto__` or `constructor` as
+ * ordinary own properties (null-prototype construction), never as prototype
+ * collisions.
+ */
interface CodeBindingNamespace {
/** The global identifier the program sees (must be a valid JS identifier). */
global: string
@@ -62,6 +80,14 @@ interface CodeBindingNamespace {
```
```ts type-equiv
+/**
+ * One host-side function exposed to the program as an async callable. The
+ * runtime bridges calls to it (possibly across a serialization boundary), so
+ * `args` and the resolution value MUST be structured-cloneable; a runtime
+ * rejects a non-cloneable value with a descriptive error rather than
+ * corrupting the run. A rejection of this function surfaces inside the
+ * program as a rejection of the corresponding call.
+ */
type CodeBindingFunction = (args: unknown) => Promise
```
@@ -72,6 +98,16 @@ type CodeBindingFunction = (args: unknown) => Promise
失败类型是**正交的结果,独立报告**(见 [defensive-patterns](../defensive-patterns.md)):预算耗尽不是异常,中止不是超时,基底崩溃(如 OOM)也不是二者中的任何一个:
```ts type-equiv
+/**
+ * Why a run failed. The kinds are orthogonal outcomes reported independently
+ * (per docs/defensive-patterns.md): a budget expiry is not an exception, an
+ * abort is not a timeout, and a substrate death is neither.
+ *
+ * - `'exception'` — the program threw or failed to parse/transform.
+ * - `'timeout'` — an implementation-owned budget expired; the message says which.
+ * - `'abort'` — {@link CodeRunRequest.signal} fired.
+ * - `'worker-exit'` — the execution substrate died without settling (e.g. OOM).
+ */
interface CodeRunFailure {
/** The failure class (see the interface doc for each kind's meaning). */
kind: 'exception' | 'timeout' | 'abort' | 'worker-exit'
diff --git a/docs/core-data-structures/compaction.i18n.yaml b/docs/core-data-structures/compaction.i18n.yaml
index f1673efb53..99025fabab 100644
--- a/docs/core-data-structures/compaction.i18n.yaml
+++ b/docs/core-data-structures/compaction.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-compaction.md: e82cc103932ad05e68bc5311dec23c3f2c1a7ce4
-compaction.zh.md: bae6e9aa385efe0a7722c2b360c0b88e87a1a779
+compaction.md: 20513bdac5a10cb634c892f42600d2f016801e09
+compaction.zh.md: 67cd89add48761d269da4034bb7f3f3752e9a1ed
diff --git a/docs/core-data-structures/compaction.zh.md b/docs/core-data-structures/compaction.zh.md
index bae6e9aa38..67cd89add4 100644
--- a/docs/core-data-structures/compaction.zh.md
+++ b/docs/core-data-structures/compaction.zh.md
@@ -2,18 +2,18 @@
[English](compaction.md) | 中文
-上下文压缩(context compaction)的 seam 是一个[能力 seam](../rfc/implemented/architecture/2026-06-13-capability-seams.md),按 bash 式拆分:接口([dsh-compact](../../packages/compact/compact),`ctx.compact`)、实现(后端,如 [dsh-compact-basic](../../packages/compact/compact-basic))、消费方(一个 `/compact` 工具,暂缓实现)。上下文压缩是**一项可选能力**,不属于 agent loop(智能体循环)主干,因此其词汇定义在此处,而非 [core.md](core.md)。基于 tokenizer 或模板的后端是实现同一接口的兄弟包。与 bash 不同的是,该接口必然依赖 `dsh-session` 和 `dsh-llm`:它的动词定义在 `Session` 之上,输出使用 `ContentBlock` 词汇(见[上下文压缩能力 seam RFC](../rfc/implemented/feature/2026-06-18-compaction-capability-seam.md))。
+压缩 seam 是一个[能力 seam](../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md),与 bash 一样分为接口([dsh-compact](../../packages/compact/compact),`ctx.compact`)、实现(例如 [dsh-compact-basic](../../packages/compact/compact-basic) 后端)和消费方(延期实现的 `/compact` 工具)。压缩是**一项可选能力**,不属于 agent loop 主干,因此其词汇定义在此而非 [core.md](core.md) 中。基于 tokenizer 或模板的后端是实现同一接口的兄弟包。与 bash 不同,该接口必然依赖 `dsh-session` 和 `dsh-llm`:其动词作用于 agent 所有的 `Session`,而其持久摘要事件使用 `ContentBlock` 词汇(见[压缩能力 seam Agent Note(agent 决策记录)](../../.agents/notes/implemented/feature/2026-06-18-compaction-capability-seam.md))。
源码:[`packages/compact/compact/src/types.ts`](../../packages/compact/compact/src/types.ts)
## `compact/*` 会话事件
-上下文压缩通过声明合并为 [`SessionEventMap`](session.md) 扩展了三种事件类型。三者均为**仅日志**事件:它们记录压缩锁及其来源信息,永远不进入 surface。`SurfaceEventType` 被刻意不扩展(只有产生消息的事件才到达模型),因此摘要本身搭载在一条独立的 `user/message` 上,带有 `surfaceOp: { op: 'replace', start, end }`——唯一的 surface 变更。关于为何复用 `user/message` 是诚实的做法而非权宜之计,见 RFC。
+压缩通过声明合并为 [`SessionEventMap`](session.md) 扩展三种事件类型。三者都**仅写入日志**——记录压缩锁及其 provenance,绝不进入 surface。这里有意不扩展 `SurfaceEventType`(只有产生消息的事件才到达模型),因此摘要本身承载在另一条带有 `surfaceOp: { op: 'replace', start, end }` 的 `user/message` 上——这是摘要压缩执行的唯一 surface 变更。关于复用 `user/message` 为何是如实建模而非权宜之计,见对应 Agent Note。
| 事件 | 载荷 | 作用 |
|---|---|---|
| `compact/start` | `{ turn }` | 获取日志记录的锁 |
-| `compact/summary` | `{ summary, shadowedRange, shadowedSeqs, shadowedTokenCount, model, maxTokens? }` | 来源信息:摘要块、被遮蔽的 surface 边界对(`start`/`end` seq,是位置跨度而非数值区间)、按 surface 顺序排列的被遮蔽 seq、估算的 token 数量,以及摘要调用的信封(`model`,加上生效时的生成上限)。记录这些信息使得单次请求可从日志加代码重建(reconstructability RFC) |
+| `compact/summary` | `{ summary, shadowedRange, shadowedSeqs, shadowedTokenCount, provider, model, maxTokens? }` | provenance:摘要 block、被遮蔽的 surface 边界对(`start`/`end` seq——位置跨度,而非数值区间)、按 surface 顺序排列的被遮蔽 seq、估算 token 数,以及摘要调用的 envelope(`provider`、`model`,若有生成上限则还包括该上限)——写入日志后,该一次性请求可由日志 + 代码重建(见可重建性 Agent Note) |
| `compact/end` | `{ turn, error? }` | 释放锁(摘要调用抛出异常时设置 `error`) |
锁括住**整个**操作:先追加 `compact/start`,然后执行摘要生成、写入 `compact/summary` 来源记录与 `user/message` 替换,最后才追加 `compact/end`。最后释放锁意味着操作中途崩溃会表现为可检测的遗留锁(有 `compact/start` 而无匹配的 `compact/end`),而非一个虚假声称压缩已完成的 `compact/end`。
@@ -22,9 +22,10 @@
## `CompactionResult`
-一次成功的压缩返回给调用方的内容:三个追加的 `compact/*` 事件的 seq、摘要块,以及被遮蔽的范围/seq 和估算的 token 数量。
+成功压缩向调用方返回:记账事件 seq、原始摘要、被遮蔽的范围与 seq,以及估算 token 数。
```ts type-equiv
+/** Result of a successful compaction operation. */
interface CompactionResult {
/** The seq of the appended `compact/start` event. */
startSeq: number
@@ -52,6 +53,45 @@ interface CompactionResult {
## 服务
-`CompactService` 暴露 `compactIfNeeded(...)` 用于压力触发的压缩(不需要压缩时返回 `null`),以及 `compactRegion(...)` 用于对显式的闭区间 surface 范围进行压缩。pre-step 调用方提供 agent、完整 prompt、会话前缀和 abort signal;实现必须将该 signal 转发给摘要生成。估算、保留策略、事件排序与摘要生成均为后端策略。
+自动调用方会说明策略为何运行;实现可以比普通压力更激进地处理已确认的溢出。
-自动压缩在串行的 `agent/pre-step` 时运行,位于步骤和请求推导之前,因此可以在替换 surface 节点的同时将 trace 事件保持在步骤之外。区域边界保持工具调用/结果配对,但不保持完整轮次,允许一个超大轮次中已关闭的早期步骤被压缩。保留策略与失败处理的细节由 `dsh-compact-basic` 负责。
+```ts type-equiv
+/** Why automatic policy is asking a backend to consider compaction. */
+type CompactionTrigger = 'pressure' | 'context-overflow'
+```
+
+`CompactService` 暴露 `compactIfNeeded(agent, trigger, signal)` 以执行自动 `pressure` 或 `context-overflow` 策略;没有可安全执行的工作时返回 `null`。它还针对显式、两端均包含的 surface 范围暴露 `compactRegion(...)`。实现必须把传入的 signal 转发给摘要流程。该 seam 不拥有计价 API:单例 [`ctx.tokenMeter`](token-meter.md) 直接拥有估算与回放,而 `dsh-compact-basic` 拥有保留策略、事件排序、按路由执行的摘要调用及其配置。
+
+压力压缩在串行 `agent/post-step` 中运行:此时成功的 assistant 输出、工具结果、缓冲 context 和 steering 已持久化,但 `step/end` 尚未发生。一旦压力或规范化溢出满足条件,compact-basic 会在选择范围前调用可选的 [`ctx.toolResultPrune`](../../packages/compact/compact-tool-result-prune/README.md),再通过 `ctx.tokenMeter` 重新测量,并且可以在不生成摘要的情况下推进 surface。失败请求的恢复在失败 step 关闭后通过 `agent/request-error` 运行;仅当 surface replacement generation 前进时才批准一个带新编号的 step 重试,即便后续摘要工作在剪枝后抛异常亦如此;取消仍然优先。区域边界保持工具调用/结果配对,但不保持整个 turn,因此一个过大 turn 中较早关闭的 step 可以被压缩。`dsh-compact-basic` 拥有阈值、保留尾部策略、溢出上限与失败处理。
+
+该 seam 导出 `toolPairingBalancedBefore(session, seq)` 与 `toolPairingBalancedAfter(session, seq)`,用于这些边缘检查。两者都会验证当前 surface 成员关系,并拒绝缺失的 seq 与孤立结果;其缓存语义由[包契约](../../packages/compact/compact/README.md#tool-pairing-boundaries)规定。
+
+## 工具结果剪枝产出
+
+可选的工具结果剪枝服务会报告每次持久内容替换以及 Unicode code point 的总减少量。其公开结果类型位于 [`compact-tool-result-prune/src/types.ts`](../../packages/compact/compact-tool-result-prune/src/types.ts)。
+
+```ts type-equiv
+/** Provenance and size accounting for one landed surface replacement. */
+interface PrunedEntry {
+ /** Full-fidelity tool-result event shadowed by the replacement. */
+ readonly originalSeq: number
+ /** Newly appended pruned tool-result event. */
+ readonly replacementSeq: number
+ /** Tool call shared by the original and replacement. */
+ readonly callId: CallId
+ /** Original text size in Unicode code points. */
+ readonly charsBefore: number
+ /** Replacement text size in Unicode code points. */
+ readonly charsAfter: number
+}
+```
+
+```ts type-equiv
+/** Aggregate outcome of one stable-surface pruning pass. */
+interface PruneResult {
+ /** Replacements in the snapshotted surface order. */
+ readonly pruned: readonly PrunedEntry[]
+ /** Total Unicode code points removed across replacements. */
+ readonly charsRemoved: number
+}
+```
diff --git a/docs/core-data-structures/core.i18n.yaml b/docs/core-data-structures/core.i18n.yaml
index a1eaa5e393..c4c4fcf9d3 100644
--- a/docs/core-data-structures/core.i18n.yaml
+++ b/docs/core-data-structures/core.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-core.md: 7ace373ae549b86f21151610719940100d6348d0
-core.zh.md: 0212dee3587d8a67bcd484a67f078d7195f6eef7
+core.md: e39650c5cc6769cd5cebe7901f92130ea57920e7
+core.zh.md: 4ab9f849ecbc30603b5c6b2875f9e9457c073c46
diff --git a/docs/core-data-structures/core.zh.md b/docs/core-data-structures/core.zh.md
index 0212dee358..4ab9f849ec 100644
--- a/docs/core-data-structures/core.zh.md
+++ b/docs/core-data-structures/core.zh.md
@@ -18,27 +18,31 @@ harness 是一个微内核:一个极小的核心加上众多插件。大多数
| 子页面 | 负责内容 |
|---|---|
| [llm-streaming.md](llm-streaming.md) | `StreamChunk` 协议格式(wire format)+ 适配器契约(adapter contract)、`BlockAssembler`、`LlmAdapter` seam |
+| [token-meter.md](token-meter.md) | 不可变的标量与位置回放度量,附带已消费日志修订号 |
| [scope.md](scope.md) | 作用域注册标识、dispatch 载体,以及拥有的 `Scope` 上下文 |
+| [goal.md](goal.md) | 持久 goal 标识、生命周期快照、激活、变更记录与 round 归属 |
+| [commands.md](commands.md) | 人类命令 seam:定义、适配器发现、直接调用、结果与解析视图 |
| [session.md](session.md) | 完整的 `SessionEventMap` 变体目录、`TurnTrigger`/`TurnEndReason`、`deriveMessages()`、轮次封闭不变式 |
| [persistence.md](persistence.md) | 持久性 seam:`SessionPersistence`、JSONL + SQLite 后端、`session/flush`、崩溃恢复、`SessionHeader` |
-| [session-query.md](session-query.md) | 逻辑会话/事件记录与有界精确事件读取 |
+| [session-query.md](session-query.md) | 逻辑记录、有界精确事件读取与关系追踪 |
+| [session-title.md](session-title.md) | 持久标题快照、来源 provenance 与异步提供方契约 |
| [system-prompt.md](system-prompt.md) | 逐次组装的上下文、工具提供方结果、prompt 段落与协作式组装 |
| [tools.md](tools.md) | `ToolDefinition` 完整字段、schema DSL、`ToolExecution`/`ToolResult`、工具展示 UI 类型,以及受保护的执行流水线 |
| [user-interaction.md](user-interaction.md) | UI 支持的人工问答 seam:`AskUserQuestionRequest`、answer/options 词汇、provider API、错误分类体系 |
| [approval.md](approval.md) | 一次性用户审批 seam:`ApprovalRequest`、`ApprovalOutcome`、逐会话策略、审计与 answerer 契约 |
-| [bash.md](bash.md) | bash 执行器 seam:`BashExecRequest`/`Spec`、`BashRunResult`、后台 `BashTask` |
-| [sandbox.md](sandbox.md) | 进程隔离 seam:文件效果模式、`SandboxPolicy`、`ConfinedArgv`、强制执行与 fail-closed 错误 |
+| [bash.md](bash.md) | bash 执行器 seam:`BashExecRequest`/`Spec`、`BashRunResult`、后台 `BashProcess` 句柄 |
+| [sandbox.md](sandbox.md) | 每会话策略解析与进程约束 seam:文件效果模式、执行/提供方策略、`ConfinedArgv`、强制执行与故障关闭错误 |
| [code-runtime.md](code-runtime.md) | 代码执行 seam:`CodeRunRequest`/`Result`、绑定命名空间、捕获日志、`CodeRunFailure` 分类体系 |
| [filesystem.md](filesystem.md) | 文件系统 seam:`FsTarget`、读/写/编辑结果、观测到的文件状态、`FsErrorCode` |
+| [lsp.md](lsp.md) | LSP 导航 seam:`LspQueryRequest`/`Result`、`LspProvider`/`Service`、四种操作、`LspError` |
| [skills.md](skills.md) | skill 服务:发现优先级、`SkillSummary`/`SkillDefinition`、会话前缀目录、面向模型的 `skill` 加载 |
| [compaction.md](compaction.md) | 压缩(compaction)seam:`compact/*` 会话事件、`CompactionResult`、`CompactService` 接口 |
| [subagent.md](subagent.md) | subagent seam:命名提供方注册表、`SubagentStartRequest`/`Result`/`Run`、启动时与运行时能力拆分 |
| [web.md](web.md) | Web 访问 seam:`WebSearchRequest`/`Result`、`WebFetchRequest`/`Result`、`WebFetchBody`、provider 可用性、`WebError` |
+| [spill.md](spill.md) | spill 存储 seam:`SaveTextSpill`、`SpillOwner`/`SpillSource`、`SpillRef`、品牌类型 `SpillLocator` |
| [workflow.md](workflow.md) | 工作流 seam:`WorkflowStartRequest`、`WorkflowMeta`、`WorkflowRun`/`Result`、`workflow/*` 事件载荷、`WorkflowError` 致命性 |
-> 本页的类型定义**逐字**粘贴自源码,并由 `pnpm run verify-type-equiv` 进行漂移检查(见 [development.md](../development.md#documenting-types-verbatim-ts-type-equiv))。为可读性省略了行内 JSDoc;完整契约请跟随源码链接查看。
-
-FIXME(catalog-verbs): the drift gate covers only the nouns (the pasted type shapes); every method surface on these pages is hand-written prose. core-data-structures should probably also generate the *verbs* — the public methods of the cataloged classes — so a signature change cannot silently outdate the catalog.
+> 这些页面上的类型声明及其 JSDoc 与源码等价,并由 `pnpm run verify-type-equiv` 检查漂移(见 [development.md](../development.md#documenting-types-verbatim-ts-type-equiv))。普通 block 保留完整声明;`public-api` block 保留去除实现体的公开 class 声明。Cordis 服务使用生成的[服务目录](../cordis-catalog/services.md)。
## `…Map → derived-union` 模式
@@ -76,25 +80,30 @@ declare module '@deepseek-ai/dsh-llm' {
## 品牌化 ID
-跨包边界的 ID 是**品牌化**的——结构上是字符串,但在类型层面不可互换(`AgentId` 不能传给期望 `CallId` 的地方)。构造通过每个类型专属的工厂函数;比较、日志和 JSON 行为与普通字符串一致。
+跨越包边界的 ID 都经过**品牌化**——结构上是字符串,但在类型层面不可互换(不能把 `SessionId` 传给需要 `CallId` 的位置)。每种类型通过各自的工厂构造;比较、日志记录和 JSON 行为与普通字符串相同。
-`Branded` 原语位于自己的纯类型包 [dsh-brand](../../packages/util/brand)(无运行时代码,不依赖 harness 包),因此任何包都可以为自己拥有的 ID 品牌化,而无需依赖不相关的能力包(例如 dsh-bash 仅通过 dsh-brand 品牌化 `BashTaskId`/`OwnerToken`,从不引入 dsh-llm)。
+`Branded` 原语位于独立的纯类型包 [dsh-brand](../../packages/util/brand) 中(没有运行时代码,也不依赖 Harness 包),因此任何包都能品牌化其拥有的 id,而无需依赖无关的能力包。
-Source: [`packages/util/brand/src/index.ts`](../../packages/util/brand/src/index.ts)
+源码:[`packages/util/brand/src/index.ts`](../../packages/util/brand/src/index.ts)
```ts type-equiv
+/** A string carrying a compile-time-only brand `B`. */
type Branded = string & { readonly [BRAND]: B }
```
-三个核心 ID:`CallId`(关联工具调用与其结果;dsh-llm)、`SessionId`(dsh-session)、`AgentId`(dsh-agent)。每个都是 `Branded<'CallId'>` 等加上同名工厂函数。能力 seam 也品牌化自己的 ID——见 [bash.md](bash.md) 中的 `BashTaskId`/`OwnerToken`。
+两个核心 ID 是 `CallId`(关联工具调用及其结果;dsh-llm)和 `SessionId`(活跃 agent 与持久 session 共享的标识;dsh-session)。能力包也会品牌化各自的 id,例如 [tasks.md](tasks.md) 中的 `TaskId`。
## 内容块与消息
一段对话由 `Message` 组成;一条消息是一个类型化**内容块**的数组。块的联合类型从 `ContentBlockMap` 派生。
-Source: [`packages/llm/llm/src/types.ts`](../../packages/llm/llm/src/types.ts)
+源码:[`packages/llm/llm/src/types.ts`](../../packages/llm/llm/src/types.ts)
```ts type-equiv
+/**
+ * Merge-extensible content blocks keyed by `type`. New core blocks must land
+ * with adapter, UI, and compaction support.
+ */
interface ContentBlockMap {
'text': TextBlock
'reasoning': ReasoningBlock
@@ -105,18 +114,44 @@ interface ContentBlockMap {
各块接口(完整字段见源码):`TextBlock`(`text`)、`ReasoningBlock`(thinking,区别于可见文本)、`ToolCallBlock`(`id: CallId`、`name`、原始 JSON `arguments`)、`ToolResultBlock`(`toolCallId`、嵌套 `content: ContentBlock[]`、`isError?`)。`ContentBlock = ContentBlockMap[ContentBlockType]`。核心集仅限于每条交付路径都尊重的块——多模态内容(图像、音频等)没有核心块类型;需要的功能通过可合并扩展的 map 添加,同时提供适配器/UI/压缩支持。
-`Message` 是角色加块:
+`Message` 由角色和 block 组成。由循环派生的 assistant 消息携带其持久 provider/model 标识,以及可选的适配器私有回放元数据:
```ts type-equiv
+/** Provider ownership and adapter-private replay data for an assistant message. */
+interface AssistantProvenance {
+ /** Provider route that produced the message. */
+ provider: string
+ /** Provider model id that produced the message. */
+ model: string
+ /**
+ * Lossless-JSON adapter state needed to replay the provider response.
+ * `LlmService` exposes it to a target adapter only when that adapter instance
+ * currently owns both this historical provider and the target provider.
+ */
+ replayState?: unknown
+}
+```
+
+```ts type-equiv
+/**
+ * A single message in a conversation history. Loop-derived assistant messages
+ * always carry provenance; callers may omit it on hand-built foreign history.
+ */
interface Message {
role: 'system' | 'user' | 'assistant'
content: ContentBlock[]
+ /** Present only on assistant messages produced by a routed adapter. */
+ provenance?: AssistantProvenance
}
```
消息来源本身也是一个可合并扩展的和类型:
```ts type-equiv
+/**
+ * Where a message (or injected content) came from.
+ * Merge-extensible sum type — plugins add their own `kind`s.
+ */
interface MessageSourceMap {
user: { kind: 'user' }
plugin: { kind: 'plugin'; plugin: string }
@@ -133,10 +168,49 @@ interface MessageSourceMap {
一次模型调用是一个完全组装好的 `GenerateOptions`。适配器以原始 `StreamChunk` 流作答;消费方用 `BlockAssembler` 组装它(见 [llm-streaming.md](llm-streaming.md))。
-Source: [`packages/llm/llm/src/types.ts`](../../packages/llm/llm/src/types.ts)
+源码:[`packages/llm/llm/src/types.ts`](../../packages/llm/llm/src/types.ts)
+
+提供方与模型发现使用小型、提供方中立的描述符。模型目录仅供参考:路由仍以已注册提供方为键,适配器也可以接受未列出的模型 id。
```ts type-equiv
+/** Display metadata for one registered provider route. */
+interface LlmProviderInfo {
+ /** Provider route key used by {@link GenerateOptions.provider}. */
+ id: string
+ /** Human-readable provider name for selectors and diagnostics. */
+ name: string
+}
+```
+
+```ts type-equiv
+/** One adapter-discovered model; catalog membership is advisory, not request validation. */
+interface LlmModelInfo {
+ /** Provider route that owns this model entry. */
+ provider: string
+ /** Model id passed to {@link GenerateOptions.model}. */
+ id: string
+ /** Human-readable model name for selectors. */
+ name: string
+ /** Optional user-facing distinction from otherwise similar models. */
+ description?: string
+}
+```
+
+对正确性敏感的模型容量与参考目录分开查询,并归服务该确切路由的适配器所有。
+
+```ts type-equiv
+/** Provider-owned context capacity for one exact provider/model route. */
+interface LlmModelContext {
+ /** Maximum combined request and response context in tokens. */
+ contextWindow: number
+}
+```
+
+```ts type-equiv
+/** A single model request, fully assembled. */
interface GenerateOptions {
+ /** Registered provider route selecting the adapter instance. */
+ provider: string
model: string
/**
* Ordered conversation messages, exactly as the provider sees them (after
@@ -163,18 +237,28 @@ interface GenerateOptions {
* it; replay uses it to keep concurrent parent and child cursors independent.
*/
sessionId?: Branded<'SessionId'>
+ /**
+ * Provider-neutral classification for an auxiliary model call. Adapters may
+ * map the purpose to model-hidden transport metadata. Ordinary conversation
+ * requests leave it unset.
+ */
+ purpose?: 'compaction'
}
```
-模型停止生成的原因是一个可合并扩展的结束原因:
+模型响应为何停止由可合并扩展的原因表示。提供方终态失败携带流式契约的 [`LlmFailure`](llm-streaming.md#llmfailure):
```ts type-equiv
+/**
+ * Why a model response stopped.
+ * Merge-extensible so adapters can surface provider-specific reasons.
+ */
interface FinishReasonMap {
'stop': { kind: 'stop' }
'tool-calls': { kind: 'tool-calls' }
'max-tokens': { kind: 'max-tokens' }
- 'aborted': { kind: 'aborted' }
- 'error': { kind: 'error'; message: string; code?: string }
+ 'aborted': { kind: 'aborted'; failure: LlmFailure }
+ 'error': { kind: 'error'; failure: LlmFailure }
}
```
@@ -183,6 +267,13 @@ interface FinishReasonMap {
`GenerateOptions.tools` 携带 `ToolSchema`——工具的 JSON Schema 描述,发送给模型。它声明在 dsh-llm(而非 dsh-tools)中,正是因为它是循环每一步组装请求的一部分:
```ts type-equiv
+/**
+ * JSON-schema description of a tool, as sent to the model.
+ *
+ * Declared here (not in dsh-tools) because it is part of {@link GenerateOptions};
+ * dsh-tools' ToolDefinition and dsh-system-prompt's PromptAssembly both import
+ * it from this package.
+ */
interface ToolSchema {
name: string
description: string
@@ -195,16 +286,22 @@ interface ToolSchema {
### 请求信封:`LlmCallConfig` 与记录的 header
-循环从已记录的状态构建每个请求。`EpochHeader` 记录调用配置、渲染后的 prompt、权威的返回工具顺序(由 `toolOrder` 配置,未设置时按字典序)以及会话前缀,通过 `request/header` 快照和 delta 实现。结合派生历史,这使得请求可从会话日志重建。见 [session.md](session.md#the-request-header-events-requestheader-and-requestheader-delta) 和[可重建请求 RFC](../rfc/implemented/architecture/2026-07-05-reconstructable-requests.md)。
+循环从已记录状态构建每个请求。`EpochHeader` 通过完整的 `request/header` 快照记录调用配置、渲染后的 prompt、权威返回工具顺序(由 `toolOrder` 配置;未配置时按字典序)以及 session prefix。结合派生历史,请求便可由会话日志重建。见 [session.md](session.md#the-request-header-event-requestheader) 与[可重建性 Agent Note(agent 决策记录)](../../.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md)。
-`agent/request` 接收一个冻结的 call-config 种子,可以返回替换值。`agent/session-prefix` 在每个循环实例中组合一次仅用于请求的前缀消息,header 记录实际使用的确切结果。到达 `llm/stream` 的请求已被深度冻结,因此突变会抛出异常。
+`agent/request` 接收冻结的调用配置种子,并可返回替代值以切换提供方、模型或采样参数。`agent/session-prefix` 为每个循环实例组合一次仅用于请求的 prefix 消息,header 记录实际使用的确切结果。到达 `llm/stream` 的请求会被深度冻结,因此变更会抛异常;请求还携带进程本地循环标识,使观察者不会把单独记录的冻结辅助调用误认成对话请求。
在协议格式上,循环构建的请求按此顺序读取:`system` 槽位(渲染后的 prompt 组装)→ `messagePrefix`(冻结的会话前缀)→ 派生历史——边界快照,其尾部在轮次首步是最新的 `user/message`,在后续步骤是上一步的工具结果。前缀从不进入派生历史;它的持久记录是 header 事件,开发不变式针对每个循环构建的请求精确重算此等式。
-FIXME(call-config-shape): revisit the exact definition of this type — which fields are genuinely epoch-level for cache purposes (`model` certainly; the sampling scalars sit here out of caution), and where provider-specific extras (reasoning options, extra body params) belong when an adapter needs them.
+FIXME(call-config-shape):重新审视此类型的精确定义——出于缓存目的,哪些字段确实属于 epoch 层级(`model` 肯定属于;采样标量目前出于谨慎放在这里),以及适配器需要时,提供方特有的额外项(推理选项、额外 body 参数)应归属何处。
```ts type-equiv
+/**
+ * Provider + model + sampling scalars of one conversation's requests. Every field maps
+ * 1:1 onto the same-named `GenerateOptions` field; the loop builds requests
+ * from the logged header rather than accepting these per call.
+ */
interface LlmCallConfig {
+ provider: string
model: string
temperature?: number
maxTokens?: number
@@ -216,9 +313,22 @@ interface LlmCallConfig {
`Session` 是一份类型化 `SessionEvent` 的**仅追加日志**——唯一的真源。LLM(大语言模型)消息历史从日志*派生*(`deriveMessages()`),而非单独存储。事件词汇从 `SessionEventMap` 派生:
-Source: [`packages/core/session/src/types.ts`](../../packages/core/session/src/types.ts)
+源码:[`packages/core/session/src/types.ts`](../../packages/core/session/src/types.ts)
```ts type-equiv
+/**
+ * One immutable entry in the session log.
+ *
+ * A proper discriminated union over `type` (not independent `type`/`data`
+ * unions), so `switch (event.type)` narrows `event.data` without casts.
+ *
+ * The {@link sourceEventSeqs} and {@link surfaceOp} fields are conditional:
+ * they only exist on {@link SurfaceEventType} variants (`user/message`,
+ * `assistant/message`, `tool/result`, `context/message`, `steering/message`).
+ * Non-surface events (boundary markers, chunks, usage, errors) never carry
+ * surface metadata — the compiler enforces this at `Session.append()`
+ * call sites.
+ */
type SessionEvent = {
[K in SessionEventType]: {
type: K
@@ -231,7 +341,9 @@ type SessionEvent = {
/**
* Seq numbers of events that are provenance sources of this event
* (e.g. the `assistant/chunk` seqs that built an `assistant/message`,
- * or the surface nodes shadowed by a compaction replace node).
+ * or the surface nodes shadowed by a compaction replace node). An
+ * `assistant/message` may carry a present empty array for a known empty
+ * provider stream; omission means unrecorded provenance.
*/
sourceEventSeqs?: number[]
/** How this event entered the surface; absent for non-surface events. */
@@ -240,157 +352,166 @@ type SessionEvent = {
}[T]
```
-十五个事件变体(`turn/start`、`turn/end`、`step/start`、`step/end`、`user/message`、`prompt/blocked`、`context/message`、`assistant/chunk`、`assistant/message`、`tool/call`、`tool/result`、`steering/message`、`todo/write`、`request/header`、`request/header-delta`)、`deriveMessages()` 投影规则、`TurnTrigger`/`TurnEndReason` 原因,以及轮次封闭不变式在 **[session.md](session.md)** 中。日志如何持久化——`SessionPersistence` seam、JSONL/SQLite 后端、`session/flush` 检查点、崩溃恢复和 `SessionHeader`——在 **[persistence.md](persistence.md)** 中。
+十四种事件变体(`turn/start`、`turn/end`、`step/start`、`step/end`、`user/message`、`prompt/blocked`、`context/message`、`assistant/chunk`、`assistant/message`、`tool/call`、`tool/result`、`steering/message`、`todo/write`、`request/header`)、`deriveMessages()` 投影规则、`TurnTrigger`/`TurnEndReason` 原因以及 turn enclosure 不变量都在 **[session.md](session.md)** 中。日志如何持久化——`SessionPersistence` seam、JSONL/SQLite 后端、`session/flush` checkpoint、崩溃恢复与 `SessionHeader`——则在 **[persistence.md](persistence.md)** 中。
## Agent 句柄
-`Agent` 是每个插件(UI、钩子、编排器)面向编程的接口。具体实现是 dsh-agent-loop 中的 `ReactLoopAgent`;循环之外没有任何东西依赖该实现。
+`Agent` 是每个插件(UI、hook、orchestrator)面向编程的 surface。具体实现为 dsh-agent-loop 包内部细节;循环外没有任何组件依赖它。
-Source: [`packages/core/agent/src/types.ts`](../../packages/core/agent/src/types.ts)
+源码:[`packages/core/agent/src/types.ts`](../../packages/core/agent/src/types.ts)
+
+`InjectOptions` 在普通消息归属信息之外,扩展了对模型隐藏的持久 JSON 元数据:
```ts type-equiv
+/** Options specific to durable synthetic context injection. */
+interface InjectOptions extends SendOptions {
+ /** Opaque JSON state retained in the session event but hidden from the model. */
+ meta?: JsonValue
+}
+```
+
+```ts type-equiv
+/** Stable runtime cause accepted by {@link Agent.cancel}. */
+type AgentCancelCause =
+ | { readonly kind: 'user' }
+ | { readonly kind: 'parent' }
+```
+
+```ts type-equiv
+/** Public agent handle; its concrete implementation is internal to `@deepseek-ai/dsh-agent-loop`. */
interface Agent {
- readonly id: AgentId
+ /** The single identity shared with {@link session}. */
+ readonly id: SessionId
readonly options: AgentOptions
readonly session: Session
readonly status: AgentStatus
-
- /**
- * The agent's scope context (`@deepseek-ai/dsh-scope`, key = this agent):
- * registrations through it — tools, prompt sections/variables, listeners,
- * restrictions — are visible to this agent only and unwind when it is
- * disposed; `agent.ctx.on('agent/…')` listeners fire only for this agent.
- */
+ /** Agent-scoped context; its contributions are agent-local, unwind on disposal, and reject registration afterward. */
readonly ctx: Context
/**
- * Queue a user message. Starts a turn when idle; otherwise waits for the next
- * turn. Content and the resolved source are accepted as one detached,
- * deeply-frozen lossless-JSON record before notification or enqueue, so
- * caller or `agent/queued` listener in-place mutation cannot change later
- * log/model input. Throws synchronously when either value is not losslessly
- * JSON-serializable; `agent/prompt-submit` may still return an explicit
- * replacement.
+ * Queue one detached, frozen lossless-JSON item. If claimed, it is the sole
+ * ordinary message in its FIFO-ordered turn; the next claimed item waits for
+ * that turn's checkpoint.
+ * Invalid input throws synchronously before notification or enqueue.
*/
send(content: ContentBlock[], options?: SendOptions): void
/**
- * Steer a running turn: content is injected between steps of the current
- * turn. Uses the same owned-value and synchronous-validation boundary as
- * {@link send}; when idle, behaves exactly like that method.
+ * Submit steering while the agent is `running`. An open turn records it at
+ * the next steering checkpoint before a request or continuation decision;
+ * policy may stop before another step. After turn close and its checkpoint,
+ * any remainder is queued for a later turn; terminal `agent/turn-stop`,
+ * cancellation, or disposal may discard it. Uses the same synchronous
+ * snapshot-and-validation boundary as {@link send}; when idle, delegates to it.
*/
steer(content: ContentBlock[], options?: SendOptions): void
/**
- * Inject in-session context (file-change notices, skill content, cron
- * notifications, …): appends a `context/message` session event the next model
- * request sees at its chronological position, rendered as tagged synthetic
- * context rather than a user prompt. Does not run the model.
- *
- * Turn-enclosure (the turn-enclosure RFC): an inject while a turn is open joins that turn;
- * an inject while idle wraps its `context/message` in a one-shot `injection`
- * turn (`turn/start` → `context/message` → `turn/end`) and checkpoints it for
- * durability, so every event stays inside a turn and a persistence backend
- * never loses a between-turn notice. The idle checkpoint is fire-and-forget
- * (inject is synchronous): a failing flush is reported via `agent/error`
- * (step `0`) and the logger, never thrown into the caller.
- *
- * Live-adapter review has validated the tagged-envelope rendering against
- * current DeepSeek behavior; provider-specific mismatches belong in that
- * adapter, not in the canonical session vocabulary.
+ * Append detached model-facing context without running the model. An open-turn
+ * injection joins at the current log position unless the current tool batch is
+ * executing; then it waits FIFO until that batch settles and drains before turn
+ * close even when interrupted. Idle injection uses a one-shot turn and durability
+ * checkpoint. Disposal awaits idle checkpoints; flush failures report through `agent/error`.
*/
- inject(content: ContentBlock[], options?: SendOptions): void
+ inject(content: ContentBlock[], options?: InjectOptions): void
/**
- * Cancel ALL pending work for the agent. `cancel()`:
- *
- * - clears the queued FIFO (un-started prompts never run) and the steering
- * FIFO (steering for the cancelled turn is dropped, not re-enqueued);
- * - aborts the in-flight step if one is running (the turn ends `aborted`);
- * - drops a turn that is about to start (a `cancel()` landing in the
- * pre-step window — after a `send()` queued but before the loop flips to
- * `running`, or after `running` is emitted but before the first step) so
- * that queued prompt does not run and cannot be batched into the cancelled
- * turn.
- *
- * After `cancel()`, `whenIdle()` resolves on the post-cancel quiescent state.
- * `cancel()` on an idle agent with nothing queued or running is a safe no-op
- * — it does NOT arm anything that would drop a later legitimate prompt.
+ * Clear all queued and steering work, including items waiting to start, and
+ * abort the active turn. An effective call first emits
+ * `agent/cancel-requested` with the resolved typed cause. The first cause wins
+ * for the active turn, and `whenIdle()` resolves after cancellation reaches
+ * quiescence. Omission means `{ kind: 'user' }`. Idle cancellation is a no-op
+ * and does not arm later work. The active turn snapshots and freezes the cause.
+ * @param cause - the stable caller intent carried by the current turn signal.
*/
- cancel(reason?: string): void
+ cancel(cause?: AgentCancelCause): void
- /**
- * Resolve once the agent has reached quiescence after settling out of
- * `running`, or immediately if it is already idle with no queued work. A
- * non-owner's quiescence-observation hook: a consumer that does NOT own the
- * agent's lifecycle awaits this to proceed only after queued/running work has
- * fully stopped, rather than returning while the driver is still streaming or
- * about to start a queued turn — without itself tearing the agent down. (A
- * lifecycle OWNER does not need it: `AgentHandle.dispose()` already awaits the
- * loop-exit promise directly as part of stopping and unregistering. So this is
- * for a non-owning observer — e.g. a test awaiting a turn to settle, or a
- * monitor — that wants the settle signal but must not dispose the agent.)
- *
- * "Quiescence", not merely "status changed": a disposed agent emits
- * `agent/status('disposed')` from inside its disposer, BEFORE the driver loop
- * has unwound — so `whenIdle()` resolving on `disposed` must wait for the loop
- * to actually exit (the implementation chains the loop-exit promise), not just
- * observe the status flip. A mid-step disposal that never reaches `idle` still
- * unblocks the await this way.
- */
+ /** Resolve at idle quiescence; disposal waits for driver exit rather than only the status transition. */
whenIdle(): Promise
- // Subagent delegation is realized on top of this interface by the
- // `@deepseek-ai/dsh-subagent` seam, not by a method here: a backend creates
- // the child through `ctx.agents.create` (fork seeds the child Session with a
- // balanced prefix of the parent's log via `CreateAgentOptions.seed`; spawn
- // starts fresh) and drives it as an ordinary Agent handle, so steer() and
- // event subscription work uniformly. See docs/core-data-structures/subagent.md.
}
```
-`AgentStatus` 为 `'idle' | 'running' | 'disposed'`,`AgentId` 是品牌化的。`AgentOptions` 可合并扩展,当前包含 `model?`。Persona 属于 `dsh-system-prompt`:agent 作用域的 `deployment:persona` 可以遮蔽全局默认值。
+`AgentStatus` 为 `'idle' | 'running' | 'disposed'`,`SessionId` 是品牌类型。`running` 描述整个驱动器的排空区间,可能跨越 turn 关闭、其持久化 checkpoint 以及连续的排队 turn;它不能证明某个 turn 仍然打开。`AgentOptions` 可合并扩展:core 声明 `provider?` 与 `model?`(在 `agent/request` 后,分发要求两者都存在)。Persona 归 `dsh-system-prompt` 所有:agent 作用域的 `deployment:persona` 可以遮蔽全局默认值。
-[事件分类体系](../architecture.md#event)拥有 `agent/*` 生命周期、检查点和 waterfall(瀑布式事件)契约。轮次和步骤边界是持久的会话事件,而非 agent 发射。
+cause 是由 TypeScript 强制约束的同进程输入。活跃持有者会把其判别字段复制到仅运行时的 `AbortSignal.reason`;该值在发布 `turn/end` 前退役。`agentInterruptReasonOf(signal)` 无需查询环境中的 initiator 状态,即可识别 `user`、`parent` 与仅用于生命周期的 `disposed`。持久 `turn/end` 保留粗粒度 `{ kind: 'aborted' }` 结果;若需记录请求 provenance,应使用单独的持久事件,而不是让终态结果承担额外含义。
+
+[事件分类](../architecture.md#event)拥有 `agent/*` 生命周期、checkpoint 与 waterfall 契约。Turn 和 step 边界是持久 session 事件,而不是 agent emit。
+
+## 发起 Agent
+
+`ctx.agents` 携带的进程本地 initiator 就是上面的确切 `Agent`,不是单独的 frame 或复制的标识。环境中存在该值既不能证明存活,也不代表授权;其生命周期与边界规则由 [initiator 作用域决策](../../.agents/notes/implemented/architecture/2026-07-15-agent-initiator-scope.md)规定。
## 拦截决策
-每个 `agent/*` 拦截 waterfall 返回一个小型的、seam 特定的类型化联合——统一的 Decision 惯用法(工具 seam 的 `PreToolDecision`/`PostToolDecision` 在 [tools.md](tools.md) 中遵循相同形状)。CC/Codex 钩子桥将其 `permissionDecision`/`decision`/`continue`/`additionalContext` 字段映射到这些类型上;原生插件直接返回它们。它们共享一个面向模型的上下文信封 `HookContext`,通过 `inject()` 作为 `context/message` 注入,因此携带一个必需的 `source`(缺少 source 会默认为 `{kind:'user'}`,将插件上下文错误标记为用户提示词)。
+每个 `agent/*` 拦截 waterfall 都返回一个小型、特定于 seam 的类型化联合——统一的 Decision 惯用形状([tools.md](tools.md) 中工具 seam 的 `PreToolDecision`/`PostToolDecision` 也采用相同形状)。CC/Codex hook bridge 把其 `permissionDecision`/`decision`/`continue`/`additionalContext` 字段映射到这些联合上;原生插件则直接返回它们。Prompt 与工具后决策共享一种面向模型的 context 形状 `HookContext`;它通过 `inject()` 作为 `context/message` 注入,因此必须携带 `source`(缺少 source 会默认成 `{kind:'user'}`,从而把插件 context 错标为用户 prompt)。其中的 `content` 作为 user-role 消息逐字到达模型,而 JSON `meta` 持久保存插件状态但不向模型暴露。两种决策都携带 `additionalContexts[]`,使每一项保留各自的 provenance 与元数据。Continuation reason 则是 steering 消息,并有意使用更窄的 content/source 形状。
-Source: [`packages/core/agent/src/types.ts`](../../packages/core/agent/src/types.ts)
+源码:[`packages/core/agent/src/types.ts`](../../packages/core/agent/src/types.ts)
```ts type-equiv
+/** Model-facing context injected by a listener; `source` prevents plugin text from being labeled as user input. */
interface HookContext {
content: ContentBlock[]
source: MessageSource
+ /** Opaque JSON state retained in the session event but hidden from the model. */
+ meta?: JsonValue
}
```
-`agent/prompt-submit` 返回 `PromptDecision`(允许一条已出队的排队消息——可选地重写其 `content` 或附加 `additionalContext`——或阻止它;一个批次中所有 prompt 都被阻止时,会打开一个零步骤轮次并以 `rejected` 结束):
+`agent/prompt-submit` 返回 `PromptDecision`(允许 turn 已领取的排队消息——可选地改写其 `content` 或附加 `additionalContexts`——或者记录 `prompt/blocked` 并以 `rejected` 结束这个零 step turn):
```ts type-equiv
+/**
+ * Prompt interception result. `allow.content` replaces the prompt and each
+ * `additionalContexts` entry becomes a separate context message. `block`
+ * records a durable `prompt/blocked` and ends the claimed prompt's zero-step
+ * turn as rejected.
+ */
type PromptDecision =
- | { kind: 'allow'; content?: ContentBlock[]; additionalContext?: HookContext }
+ | { kind: 'allow'; content?: ContentBlock[]; additionalContexts?: HookContext[] }
| { kind: 'block'; reason: string }
```
-`agent/turn-continuation` 返回 `ContinuationDecision`(循环的默认行为是:当步骤有工具调用或 steering(中途引导)被注入时 `continue`,否则 `stop`;`continue` 的 `reason` 被记录为同一轮次中下一步的 steering——类型化的 `/goal` 模式):
+`agent/turn-continuation` 返回 `ContinuationDecision`(step 有工具调用或注入了 steering 时,循环默认为 `continue`,否则为 `stop`;`continue` 的 `reason` 会记录为同一 turn 中下一 step 的 steering,因此不携带 context 元数据——即类型化 `/goal` 模式):
```ts type-equiv
+/** Turn continuation override; a continue reason is recorded as next-step steering in the same turn. */
type ContinuationDecision =
| { action: 'stop' }
- | { action: 'continue'; reason?: HookContext }
+ | { action: 'continue'; reason?: { content: ContentBlock[]; source: MessageSource } }
```
+`agent/request-error` 接收确切的原始 `RequestError`、其不可变 `LlmFailure`、在连续序列中已批准另一次请求的不可变失败列表、turn signal 以及 `next()`。恢复插件按 `failure.code` 路由,而不是按活跃错误的消息路由;每项策略只统计自身的 code,一次成功请求会清空历史:
+
+```ts type-equiv
+/** Model-request failure with an optional machine-routable provider code. */
+type RequestError = Error & { code?: string }
+```
+
+它返回 `RequestErrorDecision`;`retry` 在恢复 listener 的持久变更之后打开一个带新编号的 step,而 `fail` 在 `turn/end` 上保留结构化失败:
+
+```ts type-equiv
+/** Failed-request recovery decision; `retry` opens another numbered step while listeners delegate by calling `next()`. */
+type RequestErrorDecision = { action: 'fail' } | { action: 'retry' }
+```
+
+`agent/post-step` 会在 assistant 输出、真实或合成的工具结果、缓冲 context 与 steering 持久化之后、`step/end` 之前被 await。被取消的工具批次在排空后携带 aborted signal 到达这里;其签名为 `(agent, turn, step, signal)`,可回放事实保留在 session 日志中,而不是瞬态 payload 中。
+
`agent/turn-stop` 返回仅停止的 `ContinuationStop` 子集或 `undefined`。循环在折叠普通决策、其 reason 和待处理 steering 之后调用此串行检查点;stop 是终态,会丢弃待处理的 steering。
```ts type-equiv
+/**
+ * The terminal subset of {@link ContinuationDecision}. A listener on
+ * `agent/turn-stop` returns this to make the already-composed continuation
+ * outcome terminal; `undefined` abstains.
+ */
type ContinuationStop = Extract
```
`agent/session-start` 携带 `SessionStartSource`(会话生命周期为何开始;桥接层据此匹配其 SessionStart):
```ts type-equiv
+/** Why a session lifecycle began; seeded creates are `startup`, while persisted loads are `resume`. */
type SessionStartSource = 'startup' | 'resume' | 'clear' | 'compact'
```
diff --git a/docs/core-data-structures/filesystem.i18n.yaml b/docs/core-data-structures/filesystem.i18n.yaml
index 843abd6dc6..69cb43d21d 100644
--- a/docs/core-data-structures/filesystem.i18n.yaml
+++ b/docs/core-data-structures/filesystem.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-filesystem.md: 8bdc2323a0bf63588e01520926f093538fee4912
-filesystem.zh.md: 86b18af783899ed857f059b6b7cdb740ea357798
+filesystem.md: 3c9b041da92e71cd20429e8b1549c0b8e6f2436d
+filesystem.zh.md: 11e386c98e671f4147419eec587399a5a3bb0d07
diff --git a/docs/core-data-structures/filesystem.zh.md b/docs/core-data-structures/filesystem.zh.md
index 86b18af783..11e386c98e 100644
--- a/docs/core-data-structures/filesystem.zh.md
+++ b/docs/core-data-structures/filesystem.zh.md
@@ -13,8 +13,17 @@
每个操作首先将用户提供的路径解析为不透明的后端目标。消费方可以显示 `displayPath`,但禁止解析 `targetKey`(一个品牌化的不透明 id),也不得假设它是本地绝对路径。
```ts type-equiv
+/**
+ * A path resolved by a backend into a stable identity. `resolve()` produces
+ * this; every other operation takes it.
+ */
interface FsTarget {
+ /** Opaque key for stale guards and target lookup. */
targetKey: FsTargetKey
+ /**
+ * Path for model/UI-facing output. May be a local absolute path,
+ * workspace-relative path, or remote URI depending on the backend.
+ */
displayPath: string
}
```
@@ -22,19 +31,59 @@ interface FsTarget {
后端拥有文件版本 token,即 write/edit 所守卫的新鲜度 token。策略插件存储它们以进行陈旧检查;消费方不解释其内容。两个 id 都是品牌化的不透明字符串。
```ts type-equiv
+/**
+ * Opaque key for stale guards and target lookup. The local backend uses a
+ * realpath-like string; a remote backend might use a workspace URI or file id.
+ * Consumers MUST NOT parse it or assume it is a local absolute path.
+ */
type FsTargetKey = Branded<'FsTargetKey'>
```
```ts type-equiv
+/**
+ * Opaque file-version token — the freshness token a write/edit guards against.
+ * The local backend derives it from high-resolution stat identity and freshness
+ * fields; a remote backend might use a revision id. The policy layer records it
+ * for stale checks; consumers may display related metadata but MUST NOT
+ * interpret this token.
+ */
type FsVersion = Branded<'FsVersion'>
```
`stat` 返回元数据(从不返回内容),目标不存在时返回 `undefined`。`type` 让工具在读取前拒绝目录或特殊文件;`size` 让工具无需通过失败探测即可选择 `readText` 还是 `streamText`。
```ts type-equiv
+/**
+ * Metadata about a target — what {@link FileSystem.stat} returns. Lets the
+ * policy layer reject directories/special files before reading and choose
+ * `readText` vs `streamText` from `size` without probing by failure. `version`
+ * is the freshness token. `undefined` from `stat` means the target is absent.
+ */
interface FsInfo {
+ /** Opaque freshness token of the target right now. */
version: FsVersion
+ /** Whether the target is a regular file, a directory, or something else. */
type: 'file' | 'directory' | 'other'
+ /** Byte size of a regular file, when the backend can report it. */
+ size?: number
+}
+```
+
+`lstat` 是路径层级、不跟随链接的元数据原语。它接收路径而不是 `FsTarget`,因为 `resolve` 会有意跟随 symlink 以产生稳定标识;需要检查信任边界的消费方可以先调用 `lstat`,在解析前拒绝 `symlink`。
+
+```ts type-equiv
+/**
+ * Metadata about a path without following the final path component when it is a
+ * symbolic link. Unlike {@link FsInfo}, this path-level probe can report
+ * `symlink` so consumers with trust-boundary rules can reject repository-owned
+ * links before resolving a target.
+ */
+interface FsPathInfo {
+ /** Opaque freshness token of the path entry right now. */
+ version: FsVersion
+ /** Whether the path entry is a regular file, directory, symlink, or other. */
+ type: 'file' | 'directory' | 'symlink' | 'other'
+ /** Byte size of the path entry, when the backend can report it. */
size?: number
}
```
@@ -42,11 +91,20 @@ interface FsInfo {
`listDir` 按稳定的名称顺序返回直接子条目。每个条目携带子项的 basename、类型、已解析目标,以及后端能报告时的廉价元数据。它禁止读取文件内容,因此 `size` 仅用于普通文件,`version` 来自元数据。已损坏或已消失的子项可以作为 `other` 返回且不带元数据;列出或解析子项元数据时的权限或后端 I/O 失败会以 `FS_PERMISSION_DENIED` 或 `FS_IO_ERROR` 使整个列表操作失败。
```ts type-equiv
+/**
+ * One direct child returned by {@link FileSystem.listDir}. Listing returns
+ * metadata and resolved targets only; it must not read file contents.
+ */
interface FsDirEntry {
+ /** Basename of the child inside the listed directory. */
name: string
+ /** Whether the child is a regular file, a directory, or something else. */
type: 'file' | 'directory' | 'other'
+ /** Resolved child target for follow-up operations. */
target: FsTarget
+ /** Opaque freshness token when the backend can report metadata cheaply. */
version?: FsVersion
+ /** Byte size of a regular file, when the backend can report it. */
size?: number
}
```
@@ -56,16 +114,33 @@ interface FsDirEntry {
`writeText` 和 `editText` 的版本守卫都是可选的:省略它执行无条件(裸提供方)变更,提供它则启用守卫。`writeText` 的守卫是 `FsWriteIntent`:`createIfAbsent` 在目标缺失时创建,目标已存在时以 `FS_NOT_OBSERVED` 拒绝;`replaceIfVersion` 仅在目标存在且版本匹配时替换,否则报 `FS_STALE_VERSION`。省略 `expected` 则无条件创建或覆盖。联合类型本身只包含两种有守卫的意图;「无守卫」通过省略表达,因此 write 和 edit 共享同一个对称的 `expected?` 形状。
```ts type-equiv
+/**
+ * Guarded write intent. `createIfAbsent` rejects an existing target with
+ * `FS_NOT_OBSERVED`; `replaceIfVersion` rejects absence or mismatch with
+ * `FS_STALE_VERSION`. Omitting the intent from `writeText` means unconditional
+ * create-or-overwrite, not a third union arm.
+ */
type FsWriteIntent =
| { kind: 'createIfAbsent' }
| { kind: 'replaceIfVersion'; version: FsVersion }
```
```ts type-equiv
+/** Outcome of a full-file write. */
interface FsWriteOutcome {
+ /** Whether the write created a new file or replaced an existing one. */
operation: 'create' | 'update'
+ /** Opaque version of the file after the write. */
version: FsVersion
+ /**
+ * The file's content BEFORE the write, or `null` when the file did not exist
+ * (a create) or was undiffable (binary/non-UTF-8). LF-normalized storage text
+ * (the diff basis), never a diff — a consumer computes the result-time
+ * contextual diff from `before`/`after` when `before` is present, else falls
+ * back to a whole-file diff.
+ */
before: string | null
+ /** The file's content AFTER the write, LF-normalized to share `before`'s diff basis. */
after: string
}
```
@@ -73,17 +148,29 @@ interface FsWriteOutcome {
`editText` 是提供方级别的变更操作,而非在别处组合的 `read` 加 `write`。带守卫时,它在字面匹配之前先验证预期版本(因此对陈旧内容的编辑报 `FS_STALE_VERSION`,而非对更新内容的匹配失败);不带守卫时,它编辑当前内容。无论哪种路径,它都应用替换并原子写入——将匹配、行尾处理、陈旧检查和原子替换保持在一个变更临界区内——目标缺失时两条路径都报 `FS_STALE_VERSION`。
```ts type-equiv
+/** A literal-replacement edit request. */
interface FsEditRequest {
+ /** Literal non-empty text to replace. Must match exactly (after line-ending normalization). */
oldString: string
+ /** Literal replacement text. An empty string deletes the matched text. */
newString: string
+ /** Replace every match instead of requiring exactly one. */
replaceAll: boolean
}
```
```ts type-equiv
+/** Outcome of a literal edit. */
interface FsEditOutcome {
+ /** Opaque version of the file after the edit. */
version: FsVersion
+ /**
+ * The file's content BEFORE the edit. Raw storage text (LF-normalized by the
+ * backend), never a diff — a consumer computes the result-time contextual diff
+ * (the applied hunk with context) from `before`/`after`.
+ */
before: string
+ /** The file's content AFTER the edit. */
after: string
}
```
@@ -99,8 +186,20 @@ interface FsEditOutcome {
策略插件只需要足够的执行上下文,通过收窄 `fs/*` 事件携带的不透明 `object` actor 来推导观测状态的所有者。`ToolExecution` 满足此形状,因此 `dsh-tool-fs` 将其执行对象作为 actor 直接传递,而无需让 `dsh-fs-policy` 导入 tool、agent 或 session 包。
```ts type-equiv
+/**
+ * Minimal structural view of a tool execution the policy plugin needs to derive
+ * an observed-state owner. `@deepseek-ai/dsh-tools`' `ToolExecution` satisfies
+ * this shape, so the tool passes its `exec` straight through as the opaque
+ * `object` actor on the `fs/*` events; this plugin narrows that actor to this
+ * shape without importing `dsh-tools`, `dsh-agent`, or `dsh-session`.
+ *
+ * The owner is `agent.session` when present. It is treated as an opaque object
+ * identity (a `WeakMap` key); this package never reads any of its fields.
+ */
interface FsPolicyExec {
+ /** The agent on whose behalf the call runs, when there is one. */
agent?: {
+ /** The session that owns observed-file state, used as an opaque key. */
session?: object
}
}
@@ -111,10 +210,15 @@ interface FsPolicyExec {
文本读取受行窗口、字节上限和后端限制约束。面向模型的 `read` 工具渲染的结果纯粹是展示性的;不存在 `full`/`partial` 视图区分——授权基于新鲜度(工具直接用 stat 的版本 emit `fs/observed`),因此任何窗口化读取在文件未变时都能授权后续的 write/edit。读取窗口化与此结果形状位于 `dsh-tool-fs`(拥有读取操作的执行器)中,而非策略插件中。
```ts type-equiv
+/** Outcome of a bounded text read — what {@link formatReadOutput} renders. */
interface FileReadOutcome {
+ /** 1-based first line requested. */
offset: number
+ /** Returned lines, already numbered. */
lines: FileTextLine[]
+ /** Total line count in the file, unless `truncatedByBytes` stopped scanning early. */
totalLines: number
+ /** Whether selected output hit the byte cap before EOF or the requested limit. */
truncatedByBytes?: true
}
```
@@ -128,12 +232,18 @@ interface FileReadOutcome {
文件系统故障使用稳定的 `FsErrorCode` 字符串,由 `FsError`(`HarnessError`)携带。工具注册表在错误结果上保留 `{ name, code }`,使重试、权限和 UI 层可以按 code 分支而无需解析文本。
```ts type-equiv
+/**
+ * Stable, machine-routable codes for filesystem failures. Carried on
+ * {@link FsError}; the tool registry surfaces `{ name, code }` on `isError`
+ * results so retry/permission/UI layers can branch without parsing messages.
+ */
type FsErrorCode =
| 'FS_NOT_FOUND'
| 'FS_NOT_DIRECTORY'
| 'FS_NOT_TEXT'
| 'FS_NOT_REGULAR_FILE'
| 'FS_PERMISSION_DENIED'
+ | 'FS_SANDBOX_DENIED'
| 'FS_IO_ERROR'
| 'FS_STALE_VERSION'
| 'FS_NOT_OBSERVED'
@@ -142,8 +252,8 @@ type FsErrorCode =
| 'FS_ABORTED'
```
-`FS_NOT_DIRECTORY`、`FS_PERMISSION_DENIED` 和 `FS_IO_ERROR` 用于目录列表操作,分别区分目标存在但不是目录、列表被拒绝、以及意外的后端 I/O 故障。`FS_NOT_OBSERVED` 表示策略插件对该所有者没有先前观测记录(或 `createIfAbsent` 遇到了已存在的文件)。`FS_STALE_VERSION` 表示后端版本不再匹配已观测版本(或 edit 遇到了缺失的目标)。新鲜度授权没有 partial/full 区分,因此不存在 `FS_PARTIAL_OBSERVATION`。
+目录列表使用 `FS_NOT_DIRECTORY`、`FS_PERMISSION_DENIED` 与 `FS_IO_ERROR` 区分已存在但并非目录的目标、被拒绝的列表操作和意外的后端 I/O 失败。`FS_SANDBOX_DENIED` 是强制执行 sandbox 的后端(`dsh-fs-sandbox`)所作的策略拒绝——模式边界拒绝了写入/编辑——与 `FS_PERMISSION_DENIED`(宿主内核拒绝)不同。`FS_NOT_OBSERVED` 表示策略插件没有此所有者的先前观察记录(或 `createIfAbsent` 遇到了现有文件)。`FS_STALE_VERSION` 表示后端版本不再与观察到的版本匹配(或编辑操作遇到缺失目标)。新鲜度授权没有部分/完整之分,因此不存在 `FS_PARTIAL_OBSERVATION`。
## 服务与插件
-`FileSystem`(`ctx.fs`,抽象)拥有提供方原语:`resolve`、`stat`、`readText`、`streamText`、`listDir`、`writeText` 和 `editText`。`dsh-fs-policy` **不注册任何服务**——它是一个通过 `fs/*` 事件门控叠加策略的插件:它裁决 write/edit intent waterfall(提供 `createIfAbsent`/`replaceIfVersion`/`{ version }` 或抛出 `FS_NOT_OBSERVED`),并在 `fs/observed` 上记录。执行器是 `dsh-tool-fs`:它通过 `ctx.fs` 读取/写入/编辑,分发 waterfall,并 emit 记录事件。生成的接线目录在 [services.md](../cordis-catalog/services.md#ctxfs--filesystem-abstract-seam) 中展示确切的 `ctx.fs` 签名。
+`FileSystem`(`ctx.fs`,abstract)拥有提供方原语:`resolve`、`stat`、`lstat`、`readText`、`streamText`、`listDir`、`writeText` 与 `editText`。`dsh-fs-policy` **不注册服务**——它是一个通过 `fs/*` 事件门禁添加策略的插件:对写入/编辑意图 waterfall 作出决策(提供 `createIfAbsent`/`replaceIfVersion`/`{ version }`,或抛出 `FS_NOT_OBSERVED`),并在 `fs/observed` 上记录。执行器是 `dsh-tool-fs`:它通过 `ctx.fs` 读取/写入/编辑,分发 waterfall,并 emit 记录事件。生成的 wiring 目录在 [services.md](../cordis-catalog/services.md#ctxfs--filesystem-abstract-seam) 中展示确切的 `ctx.fs` 签名。
diff --git a/docs/core-data-structures/llm-streaming.i18n.yaml b/docs/core-data-structures/llm-streaming.i18n.yaml
index b06be9dfa6..22691c44f4 100644
--- a/docs/core-data-structures/llm-streaming.i18n.yaml
+++ b/docs/core-data-structures/llm-streaming.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-llm-streaming.md: ffd276b4647be8d10afcab0fb3c3f6daad790d20
-llm-streaming.zh.md: ea11f47e1148d21c2f23a648002c9413103628f1
+llm-streaming.md: cb99c935aea2dc9cc769e3056fdb98a2e5c9eacb
+llm-streaming.zh.md: 5dc270acc97cdeac8cf24a36c443d550e14122dc
diff --git a/docs/core-data-structures/llm-streaming.zh.md b/docs/core-data-structures/llm-streaming.zh.md
index ea11f47e11..5dc270acc9 100644
--- a/docs/core-data-structures/llm-streaming.zh.md
+++ b/docs/core-data-structures/llm-streaming.zh.md
@@ -11,6 +11,13 @@
一个流式响应交错包含多种类型的块(文本、推理(reasoning)、多个工具调用)。`index` 将每个 delta 关联到其所属块;`block-end` 携带完整组装好的 `ContentBlock`,消费方无需自行重新组装 delta。这是一个**封闭的**可辨识联合类型:对 `type` 的 `switch` 以 `assertNever` 结尾,因此新增变体会在每个必须处理它的消费方处触发编译错误。
```ts type-equiv
+/**
+ * Raw streaming protocol emitted by adapters.
+ * Block indexes correlate interleaved deltas, and `block-end` carries the
+ * assembled block. Adapters emit usage before the terminal finish and nothing
+ * afterward; tool arguments remain raw JSON strings. Failures either throw or
+ * end with `error`/`aborted`, and consumers must handle both paths.
+ */
type StreamChunk =
| { type: 'block-start'; index: number; blockType: ContentBlockType }
| { type: 'text-delta'; index: number; text: string }
@@ -18,7 +25,32 @@ type StreamChunk =
| { type: 'tool-call-delta'; index: number; id: CallId; name?: string; argumentsDelta: string }
| { type: 'block-end'; index: number; block: ContentBlock }
| { type: 'usage'; usage: TokenUsage }
- | { type: 'finish'; reason: FinishReason }
+ | {
+ type: 'finish'
+ reason: FinishReason
+ /** Adapter-private lossless-JSON state for replaying a successful response. */
+ replayState?: unknown
+ }
+```
+
+## `LlmFailure`
+
+每个抛出的失败或 final-adapter 带内失败都会规范化为一种可序列化、提供方中立的 payload。`providerRetryAfterMs` 是经校验、由提供方请求的正数延迟,而不是重试决策;`ProviderRequestId` 是用于诊断的不透明品牌字符串。
+
+```ts type-equiv
+/** Serializable provider-boundary facts; policy decides whether they are retryable. */
+interface LlmFailure {
+ /** Human-readable provider or transport failure. */
+ readonly message: string
+ /** Stable provider-neutral machine-routing code. */
+ readonly code: string
+ /** HTTP status observed at the provider boundary, when available. */
+ readonly status?: number
+ /** Provider-requested delay in milliseconds, when valid and available. */
+ readonly providerRetryAfterMs?: number
+ /** Opaque provider-issued request identifier for diagnostics. */
+ readonly requestId?: ProviderRequestId
+}
```
## 适配器契约
@@ -27,28 +59,50 @@ type StreamChunk =
- **`usage` 在 `finish` 之前,`finish` 之后不再有任何分片。** 将两者都推迟到提供方的流结束标记,这样尾部的 usage-only 分片就不会违反顺序。
- **工具调用的 `arguments` 全程保持原始 JSON 字符串。** 部分片段通过 `argumentsDelta` 流式传输;如果提供方返回的是已解析的对象,适配器在 `block-end` 时重新序列化为字符串。
-- **两条许可的错误路径。** 失败可以从 `stream()` 中 THROW(传输/协议错误),**或者**以 `finish {kind:'error'|'aborted'}` 结束流(提供方带内错误,适用于无法在流中途抛出异常的适配器)。消费方必须同时处理*两种*情况。agent loop(智能体循环)将 finish-error/aborted 转化为轮次错误,绝不会为失败的步骤记录一条正常完成的 assistant 消息。
+- **两条受支持的错误路径,一种事实形状。** 失败可以从 `stream()` 抛出(传输/协议错误),**或者**以 `finish {kind:'error'|'aborted', failure}` 结束流(无法在流中途抛异常的适配器用它表示提供方带内错误)。`LlmError.failure` 携带同一个 `LlmFailure`。final adapter 边界保留被抛出的确切 `Error` 对象,并将不可变事实关联到该调用;agent loop 关闭失败的 step,再把错误、事实与不可变的先前已重试事实提供给 `agent/request-error`。若未恢复,结构化失败会成为 turn 错误,并且该次尝试不会提交正常 assistant 消息或工具副作用。
+- **一次适配器调用就是一次提供方尝试。** 适配器禁用库重试。agent 层恢复会打开另一个持久、带编号的 step;直接调用 `ctx.llm.stream()` 的调用方仍然只尝试一次。
+- **提供方停顿在传输层受到时限约束。** 两个已交付的远程适配器都暴露正数且有限的 `streamIdleTimeoutMs`,默认五分钟。watchdog 只在 iterator `next()` 尚未完成时启动,整个请求使用同一个稳定 signal,把自身到期映射为 `TIMEOUT`,并把更早发生的调用方中止保留为 `ABORTED`。
+- **上下文溢出只有一个规范 code。** 两个 DeepSeek 适配器都通过 `isContextWindowExceededError()` 对提供方的显式细节分类并暴露 `CONTEXT_WINDOW_EXCEEDED`,无论失败以抛出的 HTTP `LlmError` 还是带内 finish error 到达。消费方按 code 路由,绝不依赖提供方文本。
- **每个提供方 HTTP 请求都携带应用归属头。** 适配器发送 `attributionHeaders()`(见下文)作为 `User-Agent` 基线,并通过协议级测试加以证明(mock 服务器断言收到的 header,或对基于库的适配器使用库的 header 钩子)。
+- **回放状态归适配器所有。** 成功的 `finish` 可以携带重建提供方原生响应所需的无损 JSON 状态。除非 `agent/step-result` listener 改写了内容,否则循环会将其与组装后的 assistant 消息一起存储。后续请求中,仅当历史提供方与目标提供方当前注册到完全相同的适配器实例时,`LlmService` 才会传递该状态。该适配器负责校验状态并拥有所有跨模型或跨提供方转换;其他适配器只会收到提供方中立的内容与 provenance,不会收到私有状态。
-这份契约正是两个适配器作为刻意配对存在的原因:`dsh-llm-deepseek`(手写 fetch/SSE(Server-Sent Events))与 `dsh-llm-pi-ai`(通过 `@earendil-works/pi-ai` 访问同一端点)。两套独立内部实现共享一份契约,正是将协议固定下来的方式:基于库的适配器无法在流中途抛出异常,因此它走通了手写适配器可能不会走到的 finish-chunk 错误路径。
+该契约由两个有意保持独立的实现锁定:`dsh-llm-deepseek`(手写 fetch/SSE)和 `dsh-llm-pi-ai`(通过 `@earendil-works/pi-ai` 实现的通用多提供方适配器)。基于库的适配器覆盖 finish-chunk 错误路径,而传输边界测试证明每个空闲 watchdog 都会停止其实际请求。
## `AppIdentity`:应用归属
-每个适配器向提供方发送的静态公开应用标识([`packages/llm/llm/src/attribution.ts`](../../packages/llm/llm/src/attribution.ts))。`attributionHeaders(identity?)` 仅将其映射为标准 `User-Agent` header;本契约有意不支持 OpenRouter 特有的应用归属 header。默认的 `APP_IDENTITY` 从 package manifest(元数据清单)获取版本号;每个字段都是公开的产品事实,不含密钥、路径、会话 id 或用户级标识符,且任何请求级信息都不得影响这些值。设计依据见 [Mandatory `User-Agent` attribution](../rfc/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.md)。
+每个适配器都会向提供方发送的静态公开应用标识([`packages/llm/llm/src/attribution.ts`](../../packages/llm/llm/src/attribution.ts))。`attributionHeaders(identity?)` 只把它映射到标准 `User-Agent` header;该契约有意不支持 OpenRouter 特有的应用归属 header。默认 `APP_IDENTITY` 从包 manifest 获取版本;每个字段都是公开产品事实——不含 secret、路径、session id 或逐用户标识,且任何逐请求信息都不得影响这些值。设计理由见[强制 `User-Agent` 归属](../../.agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.md)。
```ts type-equiv
+/**
+ * Static public application identity sent to LLM providers.
+ *
+ * Every field is a public product fact, safe on every request: no secrets,
+ * local paths, session ids, prompt text, or per-user identifiers belong here,
+ * and nothing per-request may influence the values.
+ */
interface AppIdentity {
+ /** `User-Agent` product token (lowercase, hyphenated). */
product: string
+ /** Product version; sourced from package metadata, never hand-copied. */
version: string
+ /** Public home URL of the app, used as the `User-Agent` comment. */
url: string
}
```
## `TokenUsage`
-单次调用的 token 用量统计。各计数**互不重叠**:`inputTokens` 仅为未缓存的输入;缓存命中的输入单独报告,计费输入是三者之和。如果提供方将缓存命中合并到单一的 prompt 总量中(如 DeepSeek 的 `prompt_tokens`),适配器需将其减回去。
+逐调用 token 记账。各计数**互不重叠**:`inputTokens` 只包含未缓存输入;缓存输入单独报告,计费输入是三者之和。若提供方把缓存命中折入单一 prompt 总数(如 DeepSeek 的 `prompt_tokens`),适配器会再将其扣除。`reasoningTokens` 存在时只是信息性细节,已经包含在 `outputTokens` 中;汇总时不得重复相加。
```ts type-equiv
+/**
+ * Token accounting for one model call (cache fields are optional).
+ *
+ * Counts are DISJOINT: `inputTokens` is uncached input only; cached input is
+ * reported separately as `cacheReadTokens`/`cacheWriteTokens` (billed input =
+ * sum of the three). Adapters whose providers fold cache hits into a total
+ * prompt count (DeepSeek's `prompt_tokens`) subtract them out.
+ */
interface TokenUsage {
inputTokens: number
outputTokens: number
@@ -60,15 +114,99 @@ interface TokenUsage {
## `BlockAssembler`
-`BlockAssembler`([`packages/llm/llm/src/assembler.ts`](../../packages/llm/llm/src/assembler.ts))是唯一的共享实现,将 `StreamChunk` 流折叠回 `ContentBlock` 列表与最终的 `Message`。agent loop 记录原始分片(保证回放保真度),同时将相同的分片送入 assembler,因此权威日志保留了 token 级细节,而派生消息可确定性地重建。需要组装结果而不想重新实现折叠逻辑的消费方使用它。
+`BlockAssembler`([`packages/llm/llm/src/assembler.ts`](../../packages/llm/llm/src/assembler.ts))是唯一的共享实现,负责把 `StreamChunk` 流折叠回 `ContentBlock`、usage、finish reason 与 replay state。循环在记录原始 chunk 的同时,把同一批 chunk 送入 assembler,再将组装后的 assistant 内容连同其 provider/model provenance 一起存储。需要组装结果、又不想重新实现 fold 的消费方使用它。
+
+```ts public-api
+/**
+ * Incrementally assembles raw {@link StreamChunk}s into complete
+ * {@link ContentBlock}s and a final assistant {@link Message}.
+ *
+ * The agent loop feeds it while logging raw chunks for replay fidelity, then
+ * reads `blocks()` / `message()` / `usage` / `finish` once the stream ends.
+ *
+ * Tolerant of delta-only protocols (no block-start/end); deltas arriving for
+ * an index already closed by `block-end` are ignored (malformed stream) so a
+ * misbehaving adapter cannot grow memory or corrupt a completed block.
+ */
+declare class BlockAssembler {
+ /**
+ * Feed one chunk into the assembly state.
+ * @param chunk - the next raw chunk, in stream order.
+ */
+ push(chunk: StreamChunk): void;
+ /**
+ * Assemble all blocks seen so far, in stream order.
+ * @returns one block per seen index; an open block assembles from its
+ * accumulated deltas (an unknown block type never closed by `block-end` throws).
+ */
+ blocks(): ContentBlock[];
+ /** Usage from the `usage` chunk; undefined until one arrives. */
+ get usage(): TokenUsage | undefined;
+ /** Finish reason from the `finish` chunk; `{kind: 'stop'}` when the stream ended without one. */
+ get finish(): FinishReason;
+ /** Adapter-private replay state from the terminal finish chunk, if any. */
+ get replayState(): unknown;
+ /**
+ * The assembled assistant message.
+ * @returns an assistant-role message over `blocks()` (same open-block assembly rules).
+ */
+ message(): Message;
+}
+```
## seam
-`LlmAdapter` 是提供方 seam:继承它、实现 `stream()`、通过 `ctx.llm.registerAdapter(models, adapter)` 注册。`block-start`/`block-end` 的 `index` 关联加上 assembler 意味着适配器只需发出格式正确的分片,块重组不是各适配器需要操心的事。消费方接口(`ctx.llm.stream()`)与 `llm/stream` waterfall(瀑布式事件)在 [architecture.md § Content blocks and streaming](../architecture.md#content-blocks-and-streaming-dsh-llm) 中描述。
+`LlmAdapter` 是提供方 seam:创建子类、实现 `stream()`,再用 `ctx.llm.registerAdapter(providers, adapter)` 注册一个适配器实例。`GenerateOptions.provider` 选择已注册适配器;`GenerateOptions.model` 会传给该适配器,无需在生命周期启动时注册。重复提供方路由会原子失败。可选的 `providerInfo()` 与异步 `listModels()` 方法为 `LlmService.listProviders()` / `listModels()` 提供分离的 selector 元数据。该目录仅供参考,不是请求白名单:适配器仍是权威,并可接受未列出的模型 id。单独的 `resolveModelContext()` 查询会暴露确切路由上对正确性敏感的容量信息,但不会让目录成员关系具有权威性;缺失表示元数据未知,而不是路由无效。适配器查找发生在 `llm/stream` waterfall 的终端 continuation,因此 listener 可以在查找前短路调用,或路由一个可变的一次性请求。`block-start` / `block-end` 的 `index` 关联与 assembler 共同意味着适配器只需 emit 格式正确的 chunk——block 重组不是每个适配器各自的问题。消费方 surface(`ctx.llm.stream()`)与 `llm/stream` waterfall 见 [architecture.md § 内容 block 与流式传输](../architecture.md#content-blocks-and-streaming-dsh-llm)。
+
+```ts public-api
+/**
+ * Provider-wire adapter for the harness message and stream vocabulary. Register implementations
+ * with `ctx.llm.registerAdapter(providers, adapter)`. Every provider HTTP request must include
+ * `attributionHeaders()`; prove that at the wire or library header-hook boundary. The hand-rolled
+ * DeepSeek and pi-ai adapters intentionally exercise this contract through different internals.
+ */
+declare abstract class LlmAdapter {
+ /**
+ * Describe one provider route owned by this adapter.
+ * @param provider - a route passed to `registerAdapter()` for this instance.
+ * @returns detached display metadata whose id must equal `provider`.
+ */
+ providerInfo(provider: string): LlmProviderInfo;
+ /**
+ * List models this adapter can currently advertise for one owned provider.
+ * The result is advisory: an adapter may accept unlisted model ids, and
+ * consumers must not turn absence into request rejection.
+ * @param _provider - one provider route owned by this adapter.
+ * @returns discoverable models in adapter-preferred order.
+ */
+ listModels(_provider: string): Promise;
+ /**
+ * Resolve context capacity for one model accepted by this adapter. Absence
+ * means the adapter does not know the capacity, not that routing is invalid.
+ * @param _provider - one provider route owned by this adapter.
+ * @param _model - exact model id passed to {@link GenerateOptions.model}.
+ * @returns provider-owned context metadata, or `undefined` when unavailable.
+ */
+ resolveModelContext(
+ _provider: string,
+ _model: string,
+ ): Promise;
+ /**
+ * Stream one model call as raw chunks. The only required method.
+ * @param options - the fully-assembled request; implementations must honor `options.signal`.
+ * @returns the chunk stream, obeying the adapter contract documented on `StreamChunk`.
+ */
+ abstract stream(options: GenerateOptions): AsyncIterable;
+}
+```
`ContentBlockType`(`index` 关联块所携带的键集合)派生自 `ContentBlockMap`:
```ts type-equiv
+/**
+ * Merge-extensible content blocks keyed by `type`. New core blocks must land
+ * with adapter, UI, and compaction support.
+ */
interface ContentBlockMap {
'text': TextBlock
'reasoning': ReasoningBlock
diff --git a/docs/core-data-structures/persistence.i18n.yaml b/docs/core-data-structures/persistence.i18n.yaml
index 3072063a43..d8baef895b 100644
--- a/docs/core-data-structures/persistence.i18n.yaml
+++ b/docs/core-data-structures/persistence.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-persistence.md: ce7a21a5613da903a9bddd339e122bf9f899d2bd
-persistence.zh.md: 33ddda66aacc21f847dfd45702b11b5381711cce
+persistence.md: d4bb4ed1b65eb74ff03483bf3a71a1736300834e
+persistence.zh.md: 93a418b3b06dbf0d42978900ef79a0fb86ac15f7
diff --git a/docs/core-data-structures/persistence.zh.md b/docs/core-data-structures/persistence.zh.md
index 33ddda66aa..93a418b3b0 100644
--- a/docs/core-data-structures/persistence.zh.md
+++ b/docs/core-data-structures/persistence.zh.md
@@ -4,16 +4,34 @@
事件日志的**持久性 seam**。[session.md](session.md) 描述了内存中的 `Session`:仅追加的 `SessionEvent` 日志即为真源。本页描述如何使该日志持久化:抽象的 `SessionPersistence` 服务、它的后端、flush 检查点、崩溃恢复,以及随日志一同存储的元数据头。日志承载的事件词汇在生成的[持久化日志事件目录](../persistence-catalog.md)中逐项列举。
-该 seam 是典型的[能力 seam](../rfc/implemented/architecture/2026-06-13-capability-seams.md):一个抽象服务([dsh-session-persistence](../../packages/session-persistence/session-persistence),`ctx.sessionPersistence`)在已有的 `SessionEvent` 之上定义 create/append/load/list 操作,**没有并行的持久化类型**,以及两个可互换的后端,它们通过同一套 `runPersistenceContract` 测试。详见 [session-persistence RFC](../rfc/implemented/architecture/2026-06-14-session-persistence.md)。
+该 seam 是典型的[能力 seam](../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md):一个抽象服务([dsh-session-persistence](../../packages/session-persistence/session-persistence),`ctx.sessionPersistence`)在现有 `SessionEvent` 上定义 locate/create/append/load/list——**没有平行的持久化类型**——以及两个可互换、通过同一套 `runPersistenceContract` 的后端。见 [session-persistence Agent Note(agent 决策记录)](../../.agents/notes/implemented/architecture/2026-06-14-session-persistence.md)。
## flush 检查点
-`session/event` 是一个*同步*通知;持久化插件对其进行缓冲(write-behind),并在 agent loop(智能体循环)于每个轮次结束时触发的 `session/flush` 检查点处排空缓冲区。flush 使用 `ctx.parallel`(被 await):一个轮次的事件在下一个轮次开始前已被持久提交,轮次边界即提交边界。flush 拒绝时通过 `agent/error` 和 logger 报告,而非作为会话事件(那样会落在提交边界之后),因此后端保留其缓冲事件等待下一次 flush。
+`session/event` 是一个*同步*通知;持久化插件会将其缓冲(write-behind)至 `session/flush`。循环会 await 普通 turn 的 checkpoint 后再领取下一个队列项;同步的 idle `inject()` 会调度自己的 checkpoint 而不阻塞 `send()`,dispose 仍会将其排空。成功 flush 会把已关闭 turn 作为一个单元持久提交;被拒绝的 flush 通过 `agent/error` 与 logger 报告——绝不会作为已关闭 turn 之后的 session 事件——而后端会保留已缓冲事件供下次 flush 使用。
## 崩溃恢复保留被中断的轮次
后端重新加载一个在轮次中途崩溃的日志时,会发现一个已打开的 `turn/start` 却没有 `turn/end`。它**不会**截断日志:在长周期任务中,单个轮次可能非常庞大(许多步骤、大量工具输出),而这些事件在崩溃前已被持久追加。后端改为用一个合成的 `turn/end { reason: { kind: 'interrupted' } }` 关闭这个遗留轮次,保持日志平衡与轮次闭合不变式。`interrupted` 是唯一一个不由循环发出的 `TurnEndReason`(见 [session.md](session.md#why-a-turn-ended-turnendreasonmap))。
+## `SessionLocation`——可选的逐会话制品目标
+
+`SessionPersistence.locate(meta)` 会同步解析一个归后端所有的独立制品,而不会读取、创建或 flush 它。JSONL 返回其绝对目标路径;SQLite 因各 session 共享一个数据库而返回 `undefined`。因此,返回的路径可能指向尚不存在、或还不包含当前未 flush turn 的文件;它是位置提示,不是授权或新鲜度保证。
+
+```ts type-equiv
+/**
+ * A backend-resolved, per-session local artifact location. The path is an
+ * absolute target path and can name an artifact that has not materialized yet.
+ * Consumers must treat it as a location hint, never as an authorization token.
+ */
+interface SessionLocation {
+ /** Backend-specific artifact kind, for example `jsonl`. */
+ readonly kind: string
+ /** Absolute path to this session's backend-owned artifact. */
+ readonly path: string
+}
+```
+
## `SessionHeader`:日志旁的元数据
每个会话的元数据与事件日志**分开**存储:格式版本、cwd、血统与 seed 边界是存储层关注点而非对话事件,因此不进入 `SessionEventMap`,也不会到达 `deriveMessages()`。header 通过 `session.header` 附加到 `Session` 上。
@@ -21,6 +39,9 @@
源码:[`packages/core/session/src/types.ts`](../../packages/core/session/src/types.ts)
```ts type-equiv
+/**
+ * Immutable validated storage metadata, kept outside the conversation event log.
+ */
interface SessionHeader {
/**
* On-disk format version, stamped from {@link SESSION_FORMAT_VERSION} when the
@@ -37,43 +58,42 @@ interface SessionHeader {
/** The session this one was forked from (seed lineage), if any. */
readonly parentSession?: SessionId
/**
- * How many leading events were INHERITED via a seed rather than produced by
- * this session — the seed boundary. Set when a fork seeds a child with a
- * prefix of the parent's log (= the seeded prefix length); absent/0 means the
- * session produced all its own events. Persisted so a reload reconstructs the
- * boundary instead of re-deriving it from the full stored log, and so a replay
- * harness can skip the inherited prefix when deriving the child's OWN script
- * (the seeded events are the parent's, not this child's model calls).
+ * How many leading events were inherited through a seed. Persisting this
+ * boundary lets resume and replay distinguish parent history from child work.
*/
readonly seedLength?: number
+ /**
+ * Delegation depth: absent (zero) for a top-level session, parent depth + 1
+ * for a subagent child. Persisted so a recursion budget survives restart and
+ * resume — a runtime-only depth would reset a resumed child to top-level.
+ */
+ readonly delegationDepth?: number
}
```
## `CreateSessionOptions`:seed 与元数据
-通过 store 创建 `Session` 时接受 `seed`(回放/fork 已有事件日志)和 `meta`(store 折叠进 `SessionHeader` 的存储层字段)。store 填充 `version`/`id` 并默认 `createdAt`;调用方提供经过校验的绝对路径 `cwd`、`parentSession` 血统、`seedLength` seed 边界,以及仅在重建持久化会话时提供的原始 `createdAt` 以保留其值。
+通过 store 创建 `Session` 时会接收 `seed`(回放/fork 现有事件日志)与 `meta`(store 折叠进 `SessionHeader` 的存储层字段)。store 填充 `version`/`id` 并为 `createdAt` 提供默认值;调用方提供已校验的绝对 `cwd`、`parentSession` 谱系、`seedLength` 种子边界、`delegationDepth`,以及——仅在重建已持久化 session 时——需要保留的原始 `createdAt`。
```ts type-equiv
+/**
+ * Options for creating a {@link Session} via the store. `seed` replays/forks
+ * an existing event log; `meta` carries the caller-supplied storage fields the
+ * store folds into a {@link SessionHeader}.
+ */
interface CreateSessionOptions {
/** Events to seed the new session with (replay/fork). */
readonly seed?: readonly SessionEvent[]
/**
- * Creation metadata. The store fills in `version`/`id` and defaults
- * `createdAt` to now; the caller supplies the storage-level fields (validated
- * absolute `cwd`, `parentSession` lineage, the seed boundary `seedLength`, and
- * — when reconstructing a persisted session — the original `createdAt` to
- * preserve it).
- *
- * `seedLength` is EXPLICIT, not inferred from `seed.length`: a reconstruction
- * (resume/load) seeds the WHOLE stored log, so its `seed.length` is the full
- * length, not the original boundary — the caller must pass the persisted
- * boundary back. A fresh fork passes its actual seeded-prefix length.
+ * Storage metadata read once before publication. `seedLength` is explicit
+ * because a resumed seed contains the full stored log, not only its inherited prefix.
*/
readonly meta?: {
readonly cwd?: string
readonly parentSession?: SessionId
readonly createdAt?: number
readonly seedLength?: number
+ readonly delegationDepth?: number
}
}
```
@@ -82,9 +102,9 @@ interface CreateSessionOptions {
## 后端
-两者实现相同的抽象 `SessionPersistence`(在 `SessionEvent` 之上提供 create/append/load/list),并通过 `runPersistenceContract`,证明该 seam 真正与后端无关:
+两者都实现同一个抽象 `SessionPersistence`(在 `SessionEvent` 上执行 locate/create/append/load/list),并通过 `runPersistenceContract`,证明该 seam 确实与后端无关:
-- **[dsh-session-persistence-jsonl](../../packages/session-persistence/session-persistence-jsonl)**:每个会话一个仅追加的 JSONL 日志,具备崩溃安全的原子写入、上述中断轮次崩溃恢复,以及读取/回放路径。
+- **[dsh-session-persistence-jsonl](../../packages/session-persistence/session-persistence-jsonl)**——每个 session 一份仅追加的逻辑 JSONL 日志,默认存储为带 checksum 的连续 Zstandard frame,也可配置为原始行;支持崩溃安全的原子写入、中断 turn 恢复以及读取/回放路径。
- **[dsh-session-persistence-sqlite](../../packages/session-persistence/session-persistence-sqlite)**:基于 `node:sqlite`,每个 `SessionEvent` 一行。行结构 `(session_id, seq, type, time, data, source_event_seqs, surface_op)` 与事件 1:1 映射(包含可选的 surface 元数据),因此没有需要保持同步的并行持久化 schema。
-多个后端共享同一磁盘会话时,通过[共享持久化写协调器](../rfc/implemented/architecture/2026-06-18-shared-persistence-write-coordinator.md)协调写入。
+共享同一磁盘 session 的多个后端通过[共享持久化写入协调器](../../.agents/notes/implemented/architecture/2026-06-18-shared-persistence-write-coordinator.md)协调写入。
diff --git a/docs/core-data-structures/sandbox.i18n.yaml b/docs/core-data-structures/sandbox.i18n.yaml
index e68f9b2c75..1bd49e2273 100644
--- a/docs/core-data-structures/sandbox.i18n.yaml
+++ b/docs/core-data-structures/sandbox.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-sandbox.md: be8e3cd60681077ff5036915fd99520fe9685140
-sandbox.zh.md: ca21c09e7f3d0756f78d7bd1581b9b4b03a43815
+sandbox.md: 9bc05fa06f22fdc9ac9e8aacd482c1e7c2f2edec
+sandbox.zh.md: dd02041dea998221f1fa7549cb829791137b5088
diff --git a/docs/core-data-structures/sandbox.zh.md b/docs/core-data-structures/sandbox.zh.md
index ca21c09e7f..dd02041dea 100644
--- a/docs/core-data-structures/sandbox.zh.md
+++ b/docs/core-data-structures/sandbox.zh.md
@@ -11,39 +11,90 @@
`SandboxMode` 仅管控文件系统效果。`read-only` 拒绝所有写入(必需的 `/dev/null` 接收器除外);`workspace-write` 允许在工作区根目录及后端承诺的临时区域下写入;`danger-full-access` 绕过隔离。网络与进程可见性不在此处的定义范围内。
```ts type-equiv
+/**
+ * File-effect policy for confined processes. `read-only` permits only required
+ * sinks such as `/dev/null`; `workspace-write` also permits the workspace and a
+ * backend-defined temp area; `danger-full-access` bypasses confinement. Network
+ * and process visibility are outside this vocabulary.
+ */
type SandboxMode = 'read-only' | 'workspace-write' | 'danger-full-access'
```
只有前两种模式可以发送给提供方。`danger-full-access` 的消费方直接 spawn 原始 argv,不调用 `ctx.sandbox`。
```ts type-equiv
+/** A confining (non-`danger-full-access`) mode — the modes a {@link SandboxPolicy} can carry. */
type ConfinedSandboxMode = Exclude
```
强制执行程度是一个报告事实。`full` 表示后端管控了该模式承诺的所有文件效果;`partial` 表示活跃后端或较旧的内核 ABI 仅管控其中一个子集,因此要求绝对保证的消费方必须拒绝或向上暴露这一区别。
```ts type-equiv
+/**
+ * Enforcement completeness for this host. `partial` means an active backend or
+ * older kernel ABI cannot govern every promised file effect; callers requiring
+ * an absolute boundary must not treat it as `full`.
+ */
type SandboxEnforcement = 'full' | 'partial'
```
## 逐调用策略
-策略在每次调用时完全解析并随调用携带。这使得并发消费方和一次性提权重试能够向同一个提供方请求不同的边界,而无需修改提供方状态。
+完整执行策略会按每次能力调用解析并携带。它包括 `danger-full-access`,因此消费方可以只解析一次策略,再决定是否绕过约束。普通工具调用从调用 session 的不可变 cwd 派生 `workspaceRoot`;部署配置是没有 agent 时的回退值。root 会先按文件系统语义规范化,再做词法规范化,因此包含 `symlink/..` 的 cwd 会标识所生成进程实际运行的目录。
```ts type-equiv
-interface SandboxPolicy {
+/**
+ * The complete file-effect policy resolved for one capability call. The root
+ * is carried even under modes that do not consume it so callers can resolve
+ * policy once before choosing the enforcement path.
+ */
+interface SandboxExecutionPolicy {
/** The file-effect mode this execution runs under. */
- mode: ConfinedSandboxMode
+ mode: SandboxMode
/** Absolute root directory `workspace-write` may write under. */
workspaceRoot: string
}
```
+`ctx.sandboxPolicy.resolve()` 接收活跃 session;对于已批准的重试,还接收显式模式。该服务拥有优先级与 root 回退规则,使 bash 和 fs 不必重复实现。
+
+```ts type-equiv
+/** Inputs that select the sandbox policy for one capability call. */
+interface SandboxPolicyRequest {
+ /** Calling session; its immutable cwd becomes the workspace boundary. */
+ session?: Session
+ /** Explicit approved mode override, which outranks session policy. */
+ mode?: SandboxMode
+}
+```
+
+只有受约束的执行会到达 `ctx.sandbox`;其提供方策略在保留同一 root 的同时收窄模式。这使并发 session、消费方与一次性提权重试可以向同一提供方请求不同边界,而无需改变提供方状态。
+
+```ts type-equiv
+/**
+ * What one confined execution is allowed to touch — carried PER CALL, not
+ * fixed on the provider: two consumers may confine under different policies
+ * at the same instant (bash under `read-only` while a confined child agent
+ * needs its state directory writable), and an approved escalated retry is a
+ * new call with a wider policy. Defaulting/resolution is an explicit step at
+ * the consumer boundary; the provider treats the policy as fully specified.
+ */
+interface SandboxPolicy extends SandboxExecutionPolicy {
+ /** The file-effect mode this execution runs under. */
+ mode: ConfinedSandboxMode
+}
+```
+
## 包装后的 argv 与分类方言
`ConfinedArgv` 是消费方实际 spawn 的内容。除了替换后的 argv,它还携带后端的强制执行事实和两种正交的 stderr 方言。`denialSignatures` 用于识别沙箱正常工作时被隔离命令被阻止的情况。`runnerFailureSignatures` 用于识别沙箱运行器在执行命令之前拒绝或失败的情况;消费方应先检查后者,将其作为沙箱基础设施故障上报,而非普通任务失败。
```ts type-equiv
+/**
+ * A {@link SandboxProvider.confine} result: the argv to spawn in place of
+ * the caller's own, plus the enforcement completeness the selected backend
+ * achieves for it.
+ */
interface ConfinedArgv {
/** The wrapped argv (runner, profile, separator, then the caller's argv). */
argv: string[]
@@ -59,17 +110,9 @@ interface ConfinedArgv {
*/
denialSignatures: readonly string[]
/**
- * How the RUNNER ITSELF failing identifies itself: case-insensitive stderr
- * substrings produced when the sandbox binary is missing, refuses its
- * profile, or fails closed before exec'ing the command (`bwrap: `,
- * `landlock-run: `, `sandbox-exec: ` — each covers both the runner's own
- * error prefix and the shell's runner-not-found message). ORTHOGONAL to
- * {@link denialSignatures}: a denial is the confined COMMAND being blocked
- * (the sandbox working as designed); a runner failure means the command
- * NEVER RAN and must surface as a sandbox failure, not a task failure —
- * consumers check these signatures FIRST (a runner's own error text may
- * contain denial words, e.g. an unopenable grant root reporting
- * `Permission denied`).
+ * Case-insensitive signatures for runner failure before command execution.
+ * Consumers check these before denial signatures: runner failure means the
+ * command never ran, while denial means confinement worked and blocked it.
*/
runnerFailureSignatures: readonly string[]
}
diff --git a/docs/core-data-structures/scope.i18n.yaml b/docs/core-data-structures/scope.i18n.yaml
index 6d3acddaff..4067956fe6 100644
--- a/docs/core-data-structures/scope.i18n.yaml
+++ b/docs/core-data-structures/scope.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-scope.md: f95594329ee9ac83da2efcc31df377c53e64331a
-scope.zh.md: be423e62def89e03f15d438b9fd9db6fd41b68f3
+scope.md: 73a697f2843293daffff85dabf4656346f7dcd04
+scope.zh.md: b5cc21cfb3d3dbb3890d179f9a813dccb1c318ec
diff --git a/docs/core-data-structures/scope.zh.md b/docs/core-data-structures/scope.zh.md
index be423e62de..b5cc21cfb3 100644
--- a/docs/core-data-structures/scope.zh.md
+++ b/docs/core-data-structures/scope.zh.md
@@ -2,21 +2,27 @@
[English](scope.md) | 中文
-[scope 包(package)](../../packages/core/scope)提供身份标识与载体词汇,使一个注册上下文同时表达逐 agent(智能体)的可见性与共享的生命周期归属。它是一个库级原语,而非 Cordis 服务;[agent-scope 运行时设计 RFC](../rfc/implemented/architecture/2026-07-12-agent-scope-runtime-design.md#scope-routing-one-opaque-key-selects-one-layer) 阐述了实现原理,包的 [README](../../packages/core/scope/README.md) 说明了可调用 API 与过滤语义。
+[scope 包](../../packages/core/scope)提供 identity、carrier 与 scoped-layer 词汇,使同一个注册 context 同时代表逐 agent 可见性和共享生命周期所有权。它是库原语,而不是 Cordis 服务;生命周期设计理由由 [agent-scope 运行时设计 Agent Note(agent 决策记录)](../../.agents/notes/implemented/architecture/2026-07-12-agent-scope-runtime-design.md#scope-routing-one-opaque-key-selects-one-layer)规定,registry-layer 决策由[共享存储 Agent Note](../../.agents/notes/implemented/architecture/2026-07-12-scoped-layers-store.md)规定,可调用 API 与过滤语义则由包 [README](../../packages/core/scope/README.md)规定。
-源码:[`packages/core/scope/src/index.ts`](../../packages/core/scope/src/index.ts)。
+源码:[`packages/core/scope/src/index.ts`](../../packages/core/scope/src/index.ts) 与 [`packages/core/scope/src/store.ts`](../../packages/core/scope/src/store.ts)。
## 身份标识与分发载体
`ScopeKey` 是一个不透明的对象身份标识。已交付的 agent loop(智能体循环)使用活跃的 `Agent` 对象作为自身的 key,但该原语从不检视该对象。
```ts type-equiv
+/** An opaque, identity-compared scope key. */
type ScopeKey = object
```
`Scoped` 是编译期品牌标记,标注在 `scopeTarget(base, key)` 返回的不透明路由接收器上。作用域过滤的事件声明要求以此载体作为 `this` 类型,而真正的事件主体仍作为显式参数传入。
```ts type-equiv
+/**
+ * A routing-only event receiver built by {@link scopeTarget}. The type
+ * parameter records the subject type for dispatch checking; the carrier does
+ * not expose the subject's properties. Event payloads carry the real subject.
+ */
type Scoped = object & { readonly [ScopedBrand]: T }
```
@@ -25,9 +31,29 @@ type Scoped = object & { readonly [ScopedBrand]: T }
`Scope` 将带标签的注册上下文与两个拆卸接口配对。`rawDispose` 保留有序复合 effect 所需的精确 Cordis disposer 身份;`dispose()` 是面向直接调用方和竞态调用方的公共停稳边界。
```ts type-equiv
+/** A minted registration scope and its quiescent disposal boundaries. */
interface Scope {
+ /** Context through which scope-owned registrations are made. */
ctx: Context
+ /** Exact Cordis disposer, used when nesting this scope in an ordered composite effect. */
rawDispose: () => Promise | void
+ /** Dispose every scope-owned registration; racing calls await the same completion. */
dispose(): Promise
}
```
+
+## 带作用域的注册表层
+
+`ScopeLayer` 表示一个注册表在全局或确切作用域层级的完整贡献。具体 layer 可以聚合多个具名与匿名 table;整个 layer 为空时,`ScopedLayers` 可以回收带作用域状态,而不会丢弃兄弟 table。
+
+```ts type-equiv
+/** One scope's aggregate contribution to a registry. */
+interface ScopeLayer {
+ /** Whether every table in this layer is empty. */
+ isEmpty(): boolean
+}
+```
+
+`ScopedLayers` 拥有立即创建的全局 layer,以及惰性创建的确切作用域 layer。读取不会创建 layer:`peek(undefined)` 表示没有 overlay,而 `merge()` 会物化按插入顺序排列的全局具名 entry,随后是带作用域的 shadow。注册使用同一个 context 表示可见性与 Cordis effect 所有权,在可选通知前收集一个同步 undo,返回 Cordis 的确切 disposer,并且只在带作用域 layer 的完整 `ScopeLayer` 为空时回收它。
+
+`NamedEntries` 提供按插入顺序的查找与 live iteration,重复错误由调用方所有。`AnonymousEntries` 为每次 append 分配唯一标识,使相等的值仍相互独立。迭代在同一非空 table generation 内保持 live;排空 table 会让现有 iterator 与后续插入脱离。两者都返回幂等的确切 entry undo;共享的 `EntryValues` 实现接口不公开。
diff --git a/docs/core-data-structures/session-query.i18n.yaml b/docs/core-data-structures/session-query.i18n.yaml
index ff5bae0fba..297fdf7748 100644
--- a/docs/core-data-structures/session-query.i18n.yaml
+++ b/docs/core-data-structures/session-query.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-session-query.md: 444f2bb2256a43df7bd8521dfe234f771eec7181
-session-query.zh.md: 70f9737a702f84074962d9d1c7ac49a7c119f8cf
+session-query.md: 4f977b933225e4873466a379171ec3db2596a14e
+session-query.zh.md: 864dd213102c1452337e66800db4cb828a1edb8b
diff --git a/docs/core-data-structures/session-query.zh.md b/docs/core-data-structures/session-query.zh.md
index 70f9737a70..864dd21310 100644
--- a/docs/core-data-structures/session-query.zh.md
+++ b/docs/core-data-structures/session-query.zh.md
@@ -2,7 +2,7 @@
[English](session-query.md) | 中文
-对实时优先的逻辑会话语料库进行精确读取。[包(package)契约](../../packages/session-query/session-query)定义了源优先级、动态可选持久化、克隆、surface 分类、有界窗口与类型化错误。全文搜索是另一个拟议的 SQLite 阶段。
+对优先使用 live 数据的逻辑 session 集合执行精确读取与关系追踪。[包契约](../../packages/session-query/session-query)拥有来源优先级、动态可选持久化、克隆、surface 分类、有界窗口、追踪校验与类型化失败。全文搜索属于另一个拟议的 SQLite 包。
源码:[`packages/session-query/session-query/src/types.ts`](../../packages/session-query/session-query/src/types.ts)
@@ -11,58 +11,153 @@
`SessionRecord` 由跨语料库列表返回。它独立于克隆后的实时优先 header 暴露源可用性。`SessionEventRecord` 是轻量的原始日志投影;分类使用与 model-history 推导相同的 `foldSurface()` 状态转换。
```ts type-equiv
-export type SessionEventSurface = 'current' | 'shadowed' | 'log-only'
+/** Whether an event is current model context, replaced context, or raw-log-only. */
+type SessionEventSurface = 'current' | 'shadowed' | 'log-only'
```
```ts type-equiv
-export interface SessionRecord {
+/** Lightweight identity and source availability for one logical session. */
+interface SessionRecord {
+ /** Cloned session header selected from the live-preferred corpus. */
header: SessionHeader
+ /** Whether the id currently exists in `ctx.sessions`. */
live: boolean
+ /** Whether the active persistence backend currently materializes the id. */
persisted: boolean
}
```
```ts type-equiv
-export interface SessionEventRecord {
+/** Lightweight metadata for one event within a logical session. */
+interface SessionEventRecord {
+ /** Session that owns the event. */
sessionId: SessionId
+ /** Monotonic event seq within the session. */
seq: number
+ /** Discriminant of the session event. */
type: SessionEventType
+ /** Event timestamp in Unix epoch milliseconds. */
time: number
+ /** Event placement in the folded session surface. */
surface: SessionEventSurface
}
```
+## Session 谱系
+
+`SessionLineageTrace` 按由近及远的顺序携带已知 parent,并携带一片由直接 descendant 递归嵌套而成的森林。完整性判别字段使已知 root 与缺失 parent 互斥。
+
+```ts type-equiv
+/** Recursive descendant node in a session-lineage trace. */
+interface SessionLineageNode {
+ /** Detached logical-corpus record for this descendant. */
+ session: SessionRecord
+ /** Direct children, each carrying its own recursive descendants. */
+ descendants: SessionLineageNode[]
+}
+```
+
+```ts type-equiv
+/** Known ancestry and descendants for one logical session. */
+type SessionLineageTrace = {
+ /** Detached record for the session that was traced. */
+ target: SessionRecord
+ /** Known parents from the immediate parent outward. */
+ ancestors: SessionRecord[]
+ /** Complete known descendant trees rooted at the target's direct children. */
+ descendants: SessionLineageNode[]
+} & (
+ | {
+ /** The complete parent chain is present in the logical corpus. */
+ complete: true
+ /** Detached record at the top of the complete lineage. */
+ root: SessionRecord
+ }
+ | {
+ /** The parent chain leaves the visible logical corpus. */
+ complete: false
+ /** First parent id that is not present in the logical corpus. */
+ unresolvedParentId: SessionId
+ }
+)
+```
+
## 有界事件读取
请求指定一个原始 seq 及可选的邻近数量。结果携带 `SessionHeader` 而非可用性标志,使已知的实时目标可以独立于持久化健康状态。
```ts type-equiv
-export interface SessionEventReadRequest {
+/** Request for one event plus raw neighboring log context. */
+interface SessionEventReadRequest {
+ /** Session that owns the target event. */
sessionId: SessionId
+ /** Target event seq. */
seq: number
+ /** Number of preceding raw events to include. */
before?: number
+ /** Number of following raw events to include. */
after?: number
}
```
```ts type-equiv
-export interface SessionEventWindow {
+/** Full target event and a bounded raw-log window. */
+interface SessionEventWindow {
+ /** Cloned header for the live-preferred source read. */
session: SessionHeader
+ /** Full cloned target event. */
target: SessionEvent
+ /** Full cloned events from `startSeq` through `endSeq`. */
events: SessionEvent[]
+ /** First seq included in `events`. */
startSeq: number
+ /** Last seq included in `events`. */
endSeq: number
}
```
+## 事件关系
+
+事件追踪会区分位置性的 surface 替换与已记录 provenance。除 `replacementChain` 外,每个 seq 列表都包含直接链接;该链从目标沿直接 replacer 追踪到最终的位置替换。
+
+```ts type-equiv
+/** Request for direct surface and provenance relationships around one event. */
+interface SessionEventTraceRequest {
+ /** Session that owns the target event. */
+ sessionId: SessionId
+ /** Target event seq. */
+ seq: number
+}
+```
+
+```ts type-equiv
+/** Direct surface and provenance relationships for one event. */
+interface SessionEventTrace {
+ /** Lightweight target record. */
+ target: SessionEventRecord
+ /** Immediate positional replacement event, when the target was shadowed. */
+ replacedBy?: number
+ /** Positional replacers from the immediate replacement to the final replacement. */
+ replacementChain: number[]
+ /** Surface nodes directly removed when the target itself performed a replacement. */
+ replacedEventSeqs: number[]
+ /** Direct logged provenance sources in their recorded order. */
+ sourceEventSeqs: number[]
+ /** Later events that directly name the target as a provenance source, in log order. */
+ derivedEventSeqs: number[]
+}
+```
+
## 错误
封闭的 code 联合类型区分请求校验、目标缺失、surface 日志格式错误、可选后端故障与矛盾的源元数据。
```ts type-equiv
-export type SessionQueryErrorCode =
+/** Stable machine-routable failure taxonomy for exact session reads and traces. */
+type SessionQueryErrorCode =
| 'SESSION_QUERY_EVENT_NOT_FOUND'
| 'SESSION_QUERY_INVALID_CONFIG'
+ | 'SESSION_QUERY_INVALID_LINEAGE'
| 'SESSION_QUERY_INVALID_SURFACE'
| 'SESSION_QUERY_INVALID_WINDOW'
| 'SESSION_QUERY_PERSISTENCE_FAILED'
diff --git a/docs/core-data-structures/session.i18n.yaml b/docs/core-data-structures/session.i18n.yaml
index 33e1d86f7d..8f2f0b2f8a 100644
--- a/docs/core-data-structures/session.i18n.yaml
+++ b/docs/core-data-structures/session.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-session.md: 796abebbc31a54c7c341028cf0a09031ae59cd78
-session.zh.md: 04bfe84f079762091e7c4a4d77db69c053e6ea30
+session.md: d3c6ab65df29ef0df504a0a01219e36ebad8e8fd
+session.zh.md: 7d5e03f6b8d74e7b2dc0097acb1f5f78f6d3af6e
diff --git a/docs/core-data-structures/session.zh.md b/docs/core-data-structures/session.zh.md
index 04bfe84f07..7d5e03f6b8 100644
--- a/docs/core-data-structures/session.zh.md
+++ b/docs/core-data-structures/session.zh.md
@@ -11,30 +11,54 @@
仅追加的事件类型。可通过声明合并扩展:插件通过 declaration merging 声明额外的事件类型。例如[上下文压缩(context compaction) seam](compaction.md) 添加了 `compact/start` / `compact/summary` / `compact/end`,`@deepseek-ai/dsh-hook-protocol` 添加了仅记录日志的 `hook/invoked` / `hook/result` 溯源事件,用于钩子桥接。与 `compact/*` 一样,这些都不是 `SurfaceEventType`(没有 `surfaceOp`)。生成的[持久化日志事件目录](../persistence-catalog.md)列举了所有成员(核心与合并扩展的),包含其 payload、surface 标记与声明位置。
```ts type-equiv
+/**
+ * The merge-extensible, append-only source of truth for an agent interaction.
+ * Message history is derived from this log. Every event is lossless JSON and
+ * sequence numbers stay contiguous, including raw chunks, so persistence can
+ * store the canonical log verbatim.
+ */
interface SessionEventMap {
+ /**
+ * Opens turn `turn`. `trigger` records what started it — one claimed queued
+ * message or an idle-time injection. The turn is the durability/replay
+ * boundary: every event sits between a `turn/start` and its matching
+ * `turn/end` (the turn-enclosure invariant).
+ */
'turn/start': { turn: number; trigger: TurnTrigger }
+ /**
+ * Closes turn `turn` with the {@link TurnEndReason} that ended it. The loop
+ * awaits `session/flush` after an ordinary turn ends before claiming the next
+ * queued item. Success commits the turn; rejection is reported live and does
+ * not prevent later work.
+ */
'turn/end': { turn: number; reason: TurnEndReason }
+ /** Opens step `step` of turn `turn` — one model call plus the tool executions it requested. */
'step/start': { turn: number; step: number }
+ /** Closes step `step` of turn `turn`. */
'step/end': { turn: number; step: number }
- /** A user-visible prompt (queued message drained at turn start). */
+ /** A user-visible prompt (the queued message claimed for this turn). */
'user/message': { content: ContentBlock[]; source: MessageSource }
/**
- * A queued prompt an `agent/prompt-submit` listener VETOED — the durable
- * record of a blocked prompt and why. Appended in place of the `user/message`
- * the prompt would have become, so the block survives replay even in a MIXED
- * batch where another queued prompt is allowed (there the turn does not end
- * `rejected`, so the boundary reason alone would not preserve it). `content`
- * is the original prompt the listener rejected; `reason` is the veto text
- * ({@link PromptDecision} `block.reason`). NOT a {@link SurfaceEventType}: a
- * blocked prompt produces no LLM message and never reaches `deriveMessages()`.
+ * Durable record of a prompt veto and its reason. It is log-only: the blocked
+ * prompt never enters the model-visible surface, and its turn runs zero steps.
*/
'prompt/blocked': { content: ContentBlock[]; source: MessageSource; reason: string }
/**
* In-session context injection (file-change notices, subdir AGENTS.md,
* skill content, cron notifications, …). Rendered into the derived history
- * as tagged synthetic context — NOT a user prompt.
+ * as a synthetic user-role message carrying `content` verbatim — NOT a
+ * user prompt. `meta` is durable JSON state omitted from the model
+ * projection; it is also the intended channel for any future framing
+ * directive (a producer declares the frame, a dedicated renderer applies it —
+ * see the deferred note in
+ * ../../../../.agents/notes/implemented/simplification/2026-07-20-unwrap-injected-content-envelopes.md),
+ * so the surface keeps projecting `content` verbatim rather than wrapping it.
*/
- 'context/message': { content: ContentBlock[]; source: MessageSource }
+ 'context/message': {
+ content: ContentBlock[]
+ source: MessageSource
+ meta?: JsonValue
+ }
/** Raw stream chunk — token-level replay fidelity. */
'assistant/chunk': { turn: number; step: number; chunk: StreamChunk }
/**
@@ -43,69 +67,85 @@ interface SessionEventMap {
* the model output and its accounting travel together (there is no separate
* usage record). `usage` is absent when the adapter reported none.
*/
- 'assistant/message': { turn: number; step: number; content: ContentBlock[]; usage?: TokenUsage }
+ 'assistant/message': { turn: number; step: number; content: ContentBlock[]; provenance: AssistantProvenance; usage?: TokenUsage }
+ /**
+ * The model requested one tool invocation: `name` with the raw `arguments`
+ * JSON string exactly as the model produced it (unparsed). `callId` pairs the
+ * call with its `tool/result`.
+ */
'tool/call': { turn: number; step: number; callId: CallId; name: string; arguments: string }
+ /**
+ * A completed tool call's model-facing result, plus an optional tool-private
+ * `meta` presentation payload. `meta` is opaque to the core (`unknown` — the
+ * producing tool owns its shape and reads it back in `presentResult`) but MUST
+ * be JSON-serializable: `Session.append` runtime-validates all event data with
+ * `isJsonValue`, so a non-serializable `meta` is rejected at the source, and the
+ * durable log reproduces the identical card on replay. Absent unless the tool
+ * attaches one (e.g. `dsh-tool-fs` carries its result-time contextual diff here).
+ */
'tool/result': { turn: number; step: number; callId: CallId; content: ContentBlock[]; isError: boolean; error?: { name: string; code: string }; meta?: unknown }
/** Steering content injected between steps of a running turn. */
'steering/message': { turn: number; content: ContentBlock[]; source: MessageSource }
- /**
- * The agent's whole todo list, carried as a full snapshot and replaced
- * wholesale on each write — the current list is the most recent `todo/write`
- * (last-write-wins on replay, no fold). Appended by an owning agent via
- * `session.append('todo/write', { todos })`.
- *
- * NOT a {@link SurfaceEventType}: it produces no LLM message and never reaches
- * `deriveMessages()`, so it carries no `surfaceOp` and stays off the surface —
- * it is durable, replayable UI state, distinct from the conversation history.
- * It is a `SessionEventMap` member riding the existing `session/event` emit,
- * not a first-class Cordis `interface Events` notification, so it has no
- * cordis-catalog row.
- */
+ /** Whole-list snapshot; latest write wins on replay. Log-only UI state; never derived history. */
'todo/write': { todos: TodoItem[] }
/**
- * Full snapshot of the {@link EpochHeader} the NEXT request is built under,
- * with the {@link RequestHeaderReason} it was recorded whole. Appended by
- * the loop inside the step, before dispatch, on a loop instance's first
- * request-building step (`'initial'`/`'resume'`) or when a delta failed its
- * round-trip guard (`'fallback'`); always records what the request actually
- * used, post-`agent/request`. Anchors the header fold: reconstruction reads
- * the latest snapshot and applies the deltas after it. NOT a
- * {@link SurfaceEventType}: it produces no LLM message — it is the request
- * envelope, logged so every request is a pure function of the session log
- * (the reconstructability RFC).
+ * Full header for the next request, appended inside its step before dispatch.
+ * It is log-only; the latest snapshot reconstructs the request header.
*/
'request/header': { header: EpochHeader; reason: RequestHeaderReason }
- /**
- * Amendment to the folded {@link EpochHeader}: system line-trim, name-keyed
- * tools delta, whole replacement config, or whole replacement session
- * prefix (an EMPTY array encodes the transition to "none"). The
- * writer verifies `applyHeaderDelta(previous, delta)` reproduces the new
- * header exactly and falls back to a `'fallback'` `request/header` snapshot
- * when it cannot, so a logged delta ALWAYS round-trips. NOT a
- * {@link SurfaceEventType}.
- */
- 'request/header-delta': { system?: SystemDelta; tools?: ToolsDelta; config?: LlmCallConfig; messagePrefix?: Message[] }
}
```
+### `OutOfBandSessionEventMap`:受限的带外追加显式准入
+
+仅属于 `SessionEventMap` 并不表示事件可以脱离 agent loop 的常规生命周期追加。事件所有方必须通过声明合并将同一键加入这个空标记映射,`ctx.sessions.appendOutOfBand()` 才会接受该事件;派生类型还会排除所有 surface 事件。被接受的更新会并入已打开的轮次;如果没有打开的轮次,系统则为它创建一个边界配平且已刷新完成的零步骤轮次。
+
+```ts type-equiv
+/**
+ * Marker map for plugin-owned log-only events accepted by
+ * `SessionStore.appendOutOfBand()`. A plugin extends this map with the same key
+ * it adds to {@link SessionEventMap}; surface and lifecycle events stay
+ * ineligible unless their owner explicitly opts them into this narrow seam.
+ */
+interface OutOfBandSessionEventMap {}
+```
+
### `TodoItem`:一条待办项
-`todo/write` 事件全量快照的单元。刻意保持精简:一行 `content` 加一个三态 `status`(无 id、无优先级、无 `activeForm`)。列表在每次写入时整体替换,因此条目不需要稳定标识;三态 status 恰好是 ACP(Agent Client Protocol)的 `PlanEntryStatus`,UI 桥接层可以将待办列表 1:1 映射到 ACP `plan`(再合成 ACP 额外要求的优先级)。见 [todo_write RFC](../rfc/implemented/feature/2026-06-29-todo-write-tool.md)。
+这是 `todo/write` 事件全量列表快照中的单元。它有意保持精简:一行 `content` 加一个三态 `status`(没有 id、优先级或 `activeForm`);列表在每次写入时整体替换,因此条目无需稳定标识,而这三个状态值恰好对应 ACP 的 `PlanEntryStatus`,所以 UI 桥接层可以将待办列表一一映射为 ACP `plan`(并合成 ACP 额外要求的优先级)。见 [todo_write Agent Note(agent 决策记录)](../../.agents/notes/implemented/feature/2026-06-29-todo-write-tool.md)。
```ts type-equiv
-export interface TodoItem {
+/**
+ * One entry in an agent's todo list — the unit of the `todo/write`
+ * {@link SessionEventMap} event's whole-list snapshot.
+ *
+ * Deliberately minimal: a human-readable `content` line and a three-state
+ * `status`. No id, priority, or `activeForm` — the list is replaced wholesale
+ * on every write (last-write-wins), so entries need no stable identity, and the
+ * status triple is exactly the ACP `PlanEntryStatus`, so a UI bridge can map a
+ * todo list onto an ACP `plan` 1:1 (synthesizing the priority ACP additionally
+ * requires).
+ */
+interface TodoItem {
+ /** What this task is — a short imperative line shown in the UI. */
content: string
+ /** Lifecycle state. `in_progress` marks the single task being worked now. */
status: 'pending' | 'in_progress' | 'completed'
}
```
-### 请求头事件:`request/header` 与 `request/header-delta`
+### 请求头事件:`request/header`
-请求信封(`EpochHeader`:调用配置 + 渲染后的系统提示词 + 组装好的工具 schema + 会话前缀)是被记录到日志中的会话状态,使得每次对话请求都是日志的纯函数(可重建性 RFC)。`request/header` 快照(reason 为 `'initial' | 'resume' | 'fallback'`)在对话诞生、进程边界和 delta 编码回退时锚定折叠点;`request/header-delta` 事件在运行中修正它。`foldRequestHeader(events)` 可重建任一请求构建时所用的 header;写入器在记录每个 delta 前都会做往返验证,因此格式正确的日志总能折叠。两者都不是 `SurfaceEventType`,不产生 LLM 消息。
+请求信封(即 `EpochHeader`:调用配置 + 渲染后的系统提示词 + 已组装的工具 schema + 会话前缀)会作为会话状态写入日志,因此每个对话请求都是日志的纯函数(见可重建性 Agent Note)。带有 reason `'initial'` 或 `'resume'` 的完整 `request/header` 快照记录每个 agent loop 实例的边界;之后请求发生变化时,系统会以 reason `'change'` 记录另一份完整快照。`foldRequestHeader(events)` 通过选择最新快照重建请求头。该事件不是 `SurfaceEventType`,不产生 LLM 消息。
```ts type-equiv
-export interface EpochHeader {
- /** The conversation's call configuration (model + sampling scalars). */
+/**
+ * Logged request state outside derived history: call config, system prompt,
+ * tools, and prefix. The latest full `request/header` snapshot reconstructs it;
+ * canonical empty optional fields are absent.
+ */
+interface EpochHeader {
+ /** The conversation's call configuration (provider, model, and sampling scalars). */
config: LlmCallConfig
/** Rendered system prompt text; absent for a system-less request. */
system?: string
@@ -122,13 +162,26 @@ export interface EpochHeader {
}
```
-规范形式:空的系统提示词、空的工具列表和空的会话前缀均为 ABSENT 字段,与请求构建方式一致。`messagePrefix` 是 `agent/session-prefix` waterfall(瀑布式事件)产物的持久记录(请求 = `messagePrefix + derived history`);每个 agent loop(智能体循环)实例组合一次,由该实例的快照锚定,因此实际上 loop 不会产生前缀 delta。delta 分支(整数组替换,空数组编码「回到无前缀」的转换)存在是为了编解码的完备性。其他 delta payload(`SystemDelta`:公共前缀/后缀行裁剪;`ToolsDelta`:按名称键控的增/删/改)与事件一起定义在 [`packages/core/session/src/types.ts`](../../packages/core/session/src/types.ts)。
+规范形式:空系统提示词、空工具列表和空会话前缀都表示为字段缺失,与请求构建方式一致。`messagePrefix` 是 `agent/session-prefix` waterfall(瀑布式事件)产物的持久记录(请求 = `messagePrefix + derived history`);每个 agent loop(智能体循环)实例只组合一次,并包含在该实例记录的每份完整快照中。包含已移除的 `request/header-delta` 事件或完整快照原因为 `fallback` 的旧版 v0 日志,会在 seed、append 和持久化加载边界被拒绝,而不会以不完整方式回放。
## `SessionEvent`:一条日志条目
基于 `type` 的真正可辨识联合(而非独立的 `type`/`data` 联合),因此 `switch (event.type)` 能直接收窄 `event.data`,无需类型断言。`seq` 是日志中的单调递增位置(`seq = log.length`);`time` 为 epoch 毫秒。
```ts type-equiv
+/**
+ * One immutable entry in the session log.
+ *
+ * A proper discriminated union over `type` (not independent `type`/`data`
+ * unions), so `switch (event.type)` narrows `event.data` without casts.
+ *
+ * The {@link sourceEventSeqs} and {@link surfaceOp} fields are conditional:
+ * they only exist on {@link SurfaceEventType} variants (`user/message`,
+ * `assistant/message`, `tool/result`, `context/message`, `steering/message`).
+ * Non-surface events (boundary markers, chunks, usage, errors) never carry
+ * surface metadata — the compiler enforces this at `Session.append()`
+ * call sites.
+ */
type SessionEvent = {
[K in SessionEventType]: {
type: K
@@ -141,7 +194,9 @@ type SessionEvent = {
/**
* Seq numbers of events that are provenance sources of this event
* (e.g. the `assistant/chunk` seqs that built an `assistant/message`,
- * or the surface nodes shadowed by a compaction replace node).
+ * or the surface nodes shadowed by a compaction replace node). An
+ * `assistant/message` may carry a present empty array for a known empty
+ * provider stream; omission means unrecorded provenance.
*/
sourceEventSeqs?: number[]
/** How this event entered the surface; absent for non-surface events. */
@@ -152,14 +207,21 @@ type SessionEvent = {
`SessionEventType = keyof SessionEventMap`。由于 `SessionEventMap` 可通过合并扩展,对 `SessionEvent` 的 switch 语句禁止使用 `assertNever`:插件添加的变体是合法的未知值;处理已知 case 后在 `default` 中放行。
+对于 `assistant/message`,存在的 `sourceEventSeqs: []` 表示提供方流已知且完整地为空;字段缺失则表示旧格式或其他未记录溯源信息的情况。agent loop 会为每次成功的模型调用写入该字段;其他 surface 事件只要包含该字段,其列表就必须非空。
+
## Surface 类型
-五种产生消息的类型(`SurfaceEventType`:`user/message`、`assistant/message`、`tool/result`、`context/message`、`steering/message`)携带 surface 元数据,声明它们如何加入派生的 surface 链表。见 [session surface RFC](../rfc/implemented/architecture/2026-06-18-session-surface.md)。
+五种产生消息的类型(`SurfaceEventType`:`user/message`、`assistant/message`、`tool/result`、`context/message`、`steering/message`)携带 surface 元数据,用来声明它们如何加入有序的派生 surface。见 [session surface Agent Note](../../.agents/notes/implemented/architecture/2026-06-18-session-surface.md)。
### `SurfaceEventType`:事件类型中产生消息的子集
```ts type-equiv
-export type SurfaceEventType =
+/**
+ * The subset of {@link SessionEventType} values whose events produce LLM
+ * messages and are eligible to appear on the ordered surface. Only these
+ * event types may carry {@link SurfaceOp} and {@link SessionEvent.sourceEventSeqs}.
+ */
+type SurfaceEventType =
| 'user/message'
| 'assistant/message'
| 'tool/result'
@@ -170,64 +232,221 @@ export type SurfaceEventType =
### `SurfaceOp`:事件如何进入 surface
```ts type-equiv
-export type SurfaceOp =
+/**
+ * How a session event entered the ordered surface. Only valid on
+ * {@link SurfaceEventType} events.
+ *
+ * - `'append'`: added to the tail — normal path for user/assistant/tool/context
+ * messages.
+ * - `{ op: 'replace', start, end }`: replaces surface nodes from `start`
+ * (inclusive) through `end` (inclusive) with this node. Both must exist as
+ * surface nodes in the current surface. `start === end` replaces a single
+ * node. The node's {@link SessionEvent.sourceEventSeqs} must include every
+ * shadowed surface node. Used by compaction and possible other manipulations.
+ */
+type SurfaceOp =
| 'append'
| { op: 'replace'; start: number; end: number }
```
-`'append'` 是正常的尾部追加路径。`replace` 遮蔽从 `start` 到 `end`(含两端)的 surface 节点(两者都必须是有效的 surface 节点 seq;`start === end` 时只替换一个节点),并在其位置插入新节点。
+`'append'` 是常规的尾部追加路径。`replace` 会遮蔽从 `start` 到 `end`(含两端)的 surface 条目(两者都必须是有效的 surface seq;`start === end` 时仅替换单个条目),并在原位置插入新事件。
### `SurfaceIntent`:`session.append()` 的参数
```ts type-equiv
-export interface SurfaceIntent {
+/**
+ * Surface placement and provenance for {@link Session.append}. Required on
+ * message-producing events and forbidden on log-only events.
+ */
+interface SurfaceIntent {
surfaceOp: SurfaceOp
+ /**
+ * Complete known provenance source set. `assistant/message` may use a
+ * present empty array for a known empty provider stream; omission means its
+ * provenance was not recorded. Other surface events require a non-empty set
+ * when this field is present.
+ */
sourceEventSeqs?: number[]
}
```
对 `SurfaceEventType` 事件必填:每个产生消息的事件都必须声明它如何加入 surface(派生历史的唯一来源)。非 surface 类型在编译期拒绝此参数。
-### `SurfaceNode`:surface 链表中的一个节点
+此处适用相同的溯源区分:只有 `assistant/message` 可以携带存在但为空的 `sourceEventSeqs`;省略该字段并不表示其源流为空。
+
+### `SessionSurface`:实时只读 surface 投影
+
+`Session.surface` 返回会话稳定的 `SessionSurface` 视图。同一个增量管理器在提交前校验追加候选事件,并根据已提交事件推进该投影;调用方可以观察成员关系和替换代次,但不能调用校验。
```ts type-equiv
-export interface SurfaceNode {
- seq: number
- prev: number | null
- next: number | null
+/** Readonly live projection of the message-producing session events. */
+interface SessionSurface {
+ /** Current surface event sequences in model-visible order. */
+ readonly nodes: readonly number[]
+ /** Monotonic count of committed positional replacements. */
+ readonly replaceGeneration: number
}
```
### `SurfaceFoldReplacement` 与 `SurfaceFoldResult`:完整的 surface 回放
-`foldSurface(events)` 返回当前分离的节点,以及每个声明的替换范围实际遮蔽的节点 seq。`SurfaceManager` 对其增量缓存使用相同的转换函数。
+`foldSurface(events)` 返回一份独立的当前事件 seq 列表,以及每个声明的替换范围实际遮蔽的 seq。实时管理器复用同一套状态转换,但不保留替换历史。每提交一次替换,其 `replaceGeneration` 就递增一次,使增量消费方能够区分纯尾部增长与重写。
```ts type-equiv
-export interface SurfaceFoldReplacement {
+/** One replacement operation observed while folding a session surface. */
+interface SurfaceFoldReplacement {
+ /** Seq of the event that replaced the prior surface range. */
seq: number
+ /** Declared inclusive start seq of the replaced surface range. */
start: number
+ /** Declared inclusive end seq of the replaced surface range. */
end: number
+ /** Actual surface entries removed by the operation, in surface order. */
shadowedSeqs: number[]
}
```
```ts type-equiv
-export interface SurfaceFoldResult {
- nodes: SurfaceNode[]
+/** Complete result of replaying the surface operations in a session log. */
+interface SurfaceFoldResult {
+ /** Current surface event sequences in model-visible order. */
+ nodes: number[]
+ /** Replacement operations in event order. */
replacements: SurfaceFoldReplacement[]
}
```
+## `Session` public API
+
+去除方法体的声明与源码中的普通类保持同步,覆盖其公共构造函数、状态访问器、追加边界和历史投影。存储操作仍由生成的 [`ctx.sessions` 服务目录](../cordis-catalog/services.md#ctxsessions--sessionstore)记录。
+
+```ts public-api
+/**
+ * An event-sourced session: an append-only log of {@link SessionEvent}s.
+ *
+ * Plain class (not a Service) — create instances via `ctx.sessions.create()`.
+ * Seeding with an existing event log replays/forks a session.
+ */
+declare class Session {
+ /** The ordered surface over this session's event log. */
+ get surface(): SessionSurface;
+ /**
+ * Detached, deep-frozen creation metadata (format version, cwd, lineage,
+ * seed boundary). Supplied by the store via `ctx.sessions.create()`. When a
+ * `Session` is constructed bare (tests, ad-hoc replay), a minimal header is
+ * synthesized (stamped with the current {@link SESSION_FORMAT_VERSION}) so
+ * `session.header` is always present. Kept out of the event log — it is a
+ * storage concern, not replayable conversation state.
+ */
+ readonly header: SessionHeader;
+ /** The session identity, derived from its durable header's single copy. */
+ get id(): SessionId;
+ constructor(id: SessionId, seed?: readonly SessionEvent[], header?: SessionHeader);
+ /**
+ * An immutable snapshot of the append-only event log. The snapshot is reused
+ * until the next append; a previously returned array does not grow later.
+ * Events and their nested data are deep-frozen at acceptance, so neither a
+ * cast nor ordinary JavaScript can rewrite durable history.
+ */
+ get events(): readonly SessionEvent[];
+ /** The next event's sequence number — always the log length (the `seq = log.length` contiguity contract). */
+ get seq(): number;
+ /**
+ * Append one typed event to the log and synchronously notify observers via
+ * the store-owned, module-private publication hooks. The hot path never blocks
+ * on I/O — persistence plugins buffer asynchronously. Once the event enters
+ * the log, the append is committed: observer failures are logged and
+ * contained per listener, so they do not change the return value or prevent
+ * later listeners from observing the same accepted event.
+ *
+ * @param type - The event type (key of {@link SessionEventMap}).
+ * @param data - The event payload; must be JSON-serializable.
+ * @param opts - Surface metadata: `surfaceOp` controls how the event enters
+ * the ordered surface; `sourceEventSeqs` records provenance (the seq
+ * numbers of events this one derives from). REQUIRED for
+ * {@link SurfaceEventType} events (every message-producing event must
+ * declare how it joins the surface, the sole source of derived history) and
+ * rejected by the compiler for non-surface types like `turn/start` or
+ * `assistant/chunk`.
+ * @returns the logged event — its assigned `seq`/`time` plus the SNAPSHOT of
+ * `data` that entered the log, so reading `event.data` back sees the logged
+ * value, never the caller's still-mutable input.
+ * @throws if `data` or surface metadata is not losslessly JSON-serializable
+ * (BigInt, function, symbol, undefined, negative zero, non-finite number,
+ * circular reference, sparse array, or an exotic object such as
+ * Map/Set/Date/class instance), or when the candidate violates the
+ * canonical surface contract (marker shape and eligibility, unique
+ * earlier provenance, positional replacement validity, and complete
+ * shadowed-node coverage). One recursive pass reads, validates, and
+ * copies each nested value once, so a stateful getter cannot supply one value
+ * to validation and another to storage. The event log is the durable source
+ * of truth, so a bad event fails at the append site rather than later during
+ * a backend flush. A synchronous internal dispatch validation failure or an
+ * append reentered while this acceptance/publication boundary is open also
+ * rejects before the log changes.
+ */
+ append(
+ type: T,
+ data: SessionEventMap[T],
+ ...opts: T extends SurfaceEventType ? [opts: SurfaceIntent] : []
+ ): SessionEvent;
+ /**
+ * The {@link EpochHeader} in force after the log's last header event — the
+ * header the NEXT request will be compared against — or undefined before
+ * the first `request/header` snapshot. The live, incrementally-maintained
+ * form of `foldRequestHeader(session.events)`: each header event is folded
+ * once, when first seen, so a per-step read costs O(new events).
+ * @returns the folded header, or undefined when no header event exists yet.
+ */
+ requestHeader(): EpochHeader | undefined;
+ /**
+ * Derive the LLM message history by walking the ordered sequences of
+ * message-producing events maintained by `surfaceOp` markers. The
+ * surface is the single source of derived history: every message-producing
+ * append records its `surfaceOp`, so a raw event with no marker (a chunk, a
+ * turn boundary) is correctly absent, and a compaction `replace` deletes the
+ * shadowed nodes from the derivation. The projection rules are
+ * {@link deriveEventMessage}, folded per node.
+ *
+ * CACHED: each surface node is projected exactly once, when first seen — a
+ * call costs O(new nodes), and a surface rewrite (a `replace`;
+ * {@link SessionSurface.replaceGeneration}) rebuilds. The returned array is
+ * a fresh snapshot per call (later appends never grow an array a caller
+ * already holds); the `Message` objects in it are SHARED and **deep-frozen**.
+ * Their content reuses the already frozen durable event data, so the cache
+ * needs no second deep clone and consumers still cannot mutate the log.
+ * @returns a fresh array of the shared, frozen derived history.
+ */
+ deriveMessages(): Message[];
+ /**
+ * Project a single event into the LLM message it derives to, or null when
+ * it produces none — a non-surface event (chunk, boundary, log-only record)
+ * or an empty-content assistant/message (which exists only to host usage).
+ * The per-node pure function {@link deriveMessages} folds over the surface;
+ * an external reconstructor (or the dev invariant) folds the same function
+ * over a log prefix's surface to rebuild the exact messages any request was
+ * built from (the reconstructability Agent Note). The returned message wrapper is
+ * fresh; its content reuses the logged event's already deep-frozen durable
+ * data, so changing the wrapper cannot rewrite the log and changing content
+ * throws.
+ * @param event - the event to project.
+ * @returns the derived message, or null when the event produces none.
+ */
+ deriveEventMessage(event: SessionEvent): Message | null;
+}
+```
+
## 派生历史:`deriveMessages()` 与 `deriveEventMessage()`
`Session.deriveMessages()` 将事件日志投影为模型看到的 `Message[]`。它是缓存的(每个 surface 节点在首次出现时投影一次;surface 重写触发重建)且冻结的(每次调用返回一个新数组,引用共享的深冻结消息,因此通过投影修改已记录的历史在类型上不可表达)。`deriveEventMessage(event)` 是折叠所应用的逐节点纯函数,公开暴露以便外部重建器和开发不变式检查能以完全相同的规则投影日志前缀,不会与缓存产生分歧。投影规则:
- `user/message` → 一条 user 消息。
-- `assistant/message` → 一条 assistant 消息。原始 `assistant/chunk` 事件是回放/UI 数据,在派生中被**跳过**(组装后的消息才是权威的)。**空内容**的 `assistant/message` 也被跳过:一个因 max-tokens 截断且无内容的步骤仍会记录 `assistant/message` 以承载其 `usage`,但无内容的 assistant 轮次不得进入提供方的 transcript(文本记录)。
+- `assistant/message` → 一条 assistant 消息,包含事件的提供方/模型溯源信息和可选的适配器私有回放状态。原始 `assistant/chunk` 事件属于回放/UI 数据,在派生时会被**跳过**(组装后的消息才是权威)。**内容为空的** `assistant/message` 也会跳过:因 max-tokens 而截断且无内容的步骤仍会记录一条 `assistant/message` 以承载用量和溯源信息,但无内容的 assistant 轮次不得进入提供方 transcript(文本记录)。
- `tool/result` → 一条携带 `tool-result` 块的 user 消息。
-- `context/message`、`steering/message` → 以 user 角色、按时间顺序插入的消息,包裹在标记信封中(`…`),即「系统提醒」模式;模型通过信封区分它们与真实提示词。
+- `context/message` → 按时间顺序在相应位置生成一条 user-role 消息,并原样承载其 `content`。可选的 JSON `meta` 保留在事件日志中,绝不渲染。
+- `steering/message` → 按时间顺序在相应位置生成一条 user-role 消息,并原样承载其内容。
-其他一切(`turn/*`、`step/*`)是结构性事件,不投影为消息。token 用量通过 `assistant/message.usage` 观察(产生该用量的步骤);操作错误的步骤号在 `turn/end.reason` 中(`kind: 'error'` 时)。
+其余所有事件(`turn/*`、`step/*`、插件所有的 `llm/retry`)均为结构信息,不会投影为消息。token 记账读取每个步骤的 `assistant/chunk { type: 'usage' }` 记录;如果没有用量分片,则将 `assistant/message.usage` 作为已提交步骤的后备。失败的模型请求尝试没有 assistant 消息,因此其用量分片是持久化的记账记录。操作错误的步骤号记录在 `turn/end.reason`(`kind: 'error'`)中;如果是最终模型请求失败,其中包含规范化的 `LlmFailure` 事实,其他实时错误则包含消息/代码。由于这一尚未发布的格式有意不提供兼容性承诺,seed/load 校验会拒绝缺少提供方和模型的请求头,以及缺少提供方/模型溯源信息的 assistant 消息,而不会猜测历史数据应走的提供方路由。
## 活跃会话 fork API
@@ -240,6 +459,10 @@ export interface SurfaceFoldResult {
## 轮次的触发原因:`TurnTriggerMap`
```ts type-equiv
+/**
+ * What started a turn.
+ * Merge-extensible sum type (same pattern as MessageSourceMap).
+ */
interface TurnTriggerMap {
message: { kind: 'message'; source: MessageSource }
/**
@@ -256,57 +479,57 @@ interface TurnTriggerMap {
## 轮次的结束原因:`TurnEndReasonMap`
+`aborted` 有意作为一种粗粒度的持久结果:它只记录取消中断了实时轮次,不记录是哪个运行时调用方发起取消。仅属于运行时的调用方词汇由 [`AgentCancelCause`](core.md#the-agent-handle) 定义;未来若有审计需求,应新增独立的控制请求事件,而非让终止结果承载这一信息。
+
```ts type-equiv
+/**
+ * Why a turn ended. Merge-extensible sum type.
+ */
interface TurnEndReasonMap {
completed: { kind: 'completed' }
- aborted: { kind: 'aborted'; reason?: string }
+ /** A cancellation request interrupted the live turn. */
+ aborted: { kind: 'aborted' }
/**
* The turn failed: a step threw or the model reported a failure. `step` is the
* step number the failure occurred on (the operational error's location — the
* single durable record of an in-turn failure; live diagnostics also fire via
- * `agent/error`). `code` is the error's code when one was attached.
+ * `agent/error`). Final model-request failures retain their normalized facts
+ * as one `failure`; other turn failures retain their live Error message/code.
*/
- error: { kind: 'error'; step: number; message: string; code?: string }
+ error: { kind: 'error'; step: number } & (
+ | { failure: LlmFailure; message?: never; code?: never }
+ | { message: string; code?: string; failure?: never }
+ )
disposed: { kind: 'disposed' }
+ /** At least one step reached its output-token ceiling, even if a plugin continued the turn. */
'max-tokens': { kind: 'max-tokens' }
/**
- * The turn's entire prompt batch was BLOCKED before any step ran — every
- * drained queued message was vetoed by an `agent/prompt-submit` listener (a
- * hook). The turn still opened (so the boundary stays balanced and the block
- * is a durable in-turn fact), but ran zero steps. `reason` carries the block
- * message from the vetoing decision. Distinct from `aborted` (a user-driven
- * cancel) and `error` (a failure): the prompt was rejected by policy, not
- * interrupted or broken. A UI renders it as "prompt blocked by hook".
+ * Policy blocked the turn's claimed prompt before the first step. The
+ * zero-step turn still records a balanced durable boundary and veto reason.
*/
rejected: { kind: 'rejected'; reason: string }
/**
- * The turn never ended on its own: the process crashed mid-turn and a
- * persistence backend later closed the orphaned (open) turn on reload so the
- * log stays balanced. SYNTHESIZED by the backend's crash-recovery repair — no
- * loop ever emits this. Its events are real (they were durably appended before
- * the crash) and are PRESERVED, not discarded: a single turn can be huge in a
- * long-horizon task (many steps, large tool output), so truncating it would
- * lose real work. The marker records that the turn was cut short, not that the
- * model completed it. See the session-persistence RFC.
+ * A persistence backend closed a crash-orphaned turn on reload. The loop never
+ * emits this marker, and the events recorded before the crash remain intact.
*/
interrupted: { kind: 'interrupted' }
}
```
-`max-tokens` 对应同名的模型调用 `FinishReason`:轮次中任何一个步骤出现 `max-tokens`,整个轮次就以 `max-tokens` 结束而非 `completed`(截断事实优先于后续的继续),消费方据此区分正常停止与被截断的情况。但这仅相对于 `completed` 而言:`disposed`/`aborted`/`error` 结果优先级更高。`rejected` 是一个零步骤轮次,其整批提示词被 `agent/prompt-submit` 钩子阻止(ACP 桥接层将其映射为 `cancelled`)。`interrupted` 是唯一不由 loop 发出的原因,由崩溃恢复合成(见 [persistence.md](persistence.md))。两个 map 均可通过合并扩展。
+`max-tokens` 与模型调用中同名的 `FinishReason` 对应:只要轮次内有任何步骤以 `max-tokens` 结束,整个轮次就以 `max-tokens` 而不是 `completed` 结束(即使之后继续执行,截断事实仍优先),让消费方能够区分正常停止和截断停止;但它只优先于 `completed`,`disposed`/`aborted`/`error` 结果的优先级更高。`rejected` 表示一个零步骤轮次,其已认领的提示词被 `agent/prompt-submit` 钩子阻止(ACP 桥接层将其映射为 `cancelled`)。`interrupted` 是唯一不会由任何 loop 发出的原因:它由崩溃恢复合成(见 [persistence.md](persistence.md))。两个 map 均可通过合并扩展。
## 轮次封闭不变式
-每个会话事件都存在于一个轮次**内部**(位于 `turn/start` 与其对应的 `turn/end` 之间)。loop 在 `turn/start` *之后*追加排队的 `user/message` 事件;空闲时的 `agent.inject()` 将其 `context/message` 包裹在一个一次性的 `injection` 轮次中。这使得轮次成为唯一的持久性/回放边界:后端可以将最后一个 `turn/end` 之后的任何内容视为中断崩溃的尾部,而不会误丢合法记录的轮次间上下文。`dsh-invariants` 插件在开发环境中强制执行此不变式(在无打开轮次时追加消息事件会抛出异常)。见[轮次封闭不变式 RFC](../rfc/implemented/architecture/2026-06-15-turn-enclosure-invariant.md)。
+每个会话事件都位于一个轮次**之内**(在 `turn/start` 和对应的 `turn/end` 之间)。loop 在 `turn/start` *之后*追加已排队的 `user/message` 事件;空闲时的 `agent.inject()` 会用一次性的 `injection` 轮次包住其 `context/message`;没有打开的轮次时,`appendOutOfBand()` 同样会用一个轮次包住符合条件的仅日志事件。这使轮次成为唯一的持久性/回放边界:后端可以将最后一个 `turn/end` 之后的任何内容视为崩溃中断尾部,而不会丢失合法记录在轮次之间的上下文。可选的 `dsh-session/invariant` 配套插件通过 `ctx.invariants` 在开发环境中强制此不变式(消息事件若位于打开的轮次之外便会抛出)。见[轮次封闭不变式 Agent Note](../../.agents/notes/implemented/architecture/2026-06-15-turn-enclosure-invariant.md)。
## 插件贡献的仅日志事件
插件可以通过 declaration merging 添加额外的 `SessionEventMap` 类型。这些是**仅日志**事件:不是 `SurfaceEventType`(不携带 `surfaceOp`,不参与派生历史),但与所有事件一样,必须位于一个打开的轮次内。完整的逐事件枚举(核心与插件贡献的,含 payload 与溯源信息)见生成的[持久化日志事件目录](../persistence-catalog.md);压缩 seam 的 `compact/*` 语义在 [compaction.md](compaction.md) 中讨论。
-钩子桥接的 `hook/invoked` / `hook/result` 溯源对(来自 `@deepseek-ai/dsh-hook-protocol`)通过 `handlerId` 关联。轮次中的钩子点(`PreToolUse`/`PostToolUse`/`UserPromptSubmit`/`Stop`)在 loop 打开的轮次内触发,因此其 `hook/*` 记录天然满足轮次封闭。`SessionStart` 不产生 `hook/*` 记录(其注入的 `context/message` 就是持久证据),因为它没有打开的轮次来容纳记录(见[钩子桥接 RFC](../rfc/implemented/feature/2026-06-30-hook-bridges.md))。
+钩子桥接层的 `hook/invoked` / `hook/result` 溯源对(来自 `@deepseek-ai/dsh-hook-protocol`)通过 `handlerId` 关联。轮次中间的钩子点(`PreToolUse`/`PostToolUse`/`UserPromptSubmit`/`Stop`)在 loop 已打开的轮次内触发,因此其 `hook/*` 记录天然位于轮次之内。`SessionStart` 不生成 `hook/*` 记录:它注入的 `context/message` 已是持久证据,而且当时没有已打开的轮次可容纳该记录(见[钩子桥接 Agent Note](../../.agents/notes/implemented/feature/2026-06-30-hook-bridges.md))。
## 持久性契约
-持久化后端所依赖的约定:持久日志逐字保存每个事件,**包括** `assistant/chunk`。`seq` 必须保持连续,因此不能从规范日志中过滤掉 chunk。所有 `event.data` 必须可 JSON 序列化;`Session.append` 在源头强制执行此约束(对不可序列化的数据抛出异常),因此坏事件永远不会进入日志,`session.events` 始终等于后端能持久化的内容。添加一个携带不可序列化数据的事件类型,或破坏不变式插件所检查的 turn/step 嵌套结构,都是对磁盘格式的破坏性变更。
+持久化后端依赖的契约如下:持久日志原样保存每个事件,**包括** `assistant/chunk`;`seq` 必须连续,因此不能从规范日志中过滤分片。所有 `event.data` 都必须可序列化为 JSON;`Session.append` 会从源头强制这一要求(遇到不可序列化数据时抛出),因此错误事件绝不会进入日志,`session.events` 始终与后端可持久化的内容一致。新增携带不可序列化数据的事件类型,或破坏会话不变式配套插件所检查的轮次/步骤嵌套,会构成磁盘格式的破坏性变更。
消费此契约的后端见 [persistence.md](persistence.md)。
diff --git a/docs/core-data-structures/skills.i18n.yaml b/docs/core-data-structures/skills.i18n.yaml
index 32c97d6b0a..e71bfaa45c 100644
--- a/docs/core-data-structures/skills.i18n.yaml
+++ b/docs/core-data-structures/skills.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-skills.md: b0a847cec05651b63e63de96423170a0fd7ca2a9
-skills.zh.md: 201bf53e95b5cbf5f8873217acca3c478cf30860
+skills.md: fc9599713dcfddec9719ed746b66ea0217b86cf5
+skills.zh.md: ef67f06b69ac321d1d8bea4ef962a9ac4f6be2dd
diff --git a/docs/core-data-structures/skills.zh.md b/docs/core-data-structures/skills.zh.md
index 201bf53e95..ef67f06b69 100644
--- a/docs/core-data-structures/skills.zh.md
+++ b/docs/core-data-structures/skills.zh.md
@@ -13,9 +13,25 @@
重名按 rank、提供方顺序、本地顺序依次解决;摘要按名称排序。`list()` 拒绝时记录日志并跳过,不缓存降级后的目录;格式错误的候选项快速失败。
```ts type-equiv
+/** Provider interface for one source of skills, such as local directories or a remote registry. */
interface SkillProvider {
+ /** Unique provider name in the `ctx.skills` registry. */
readonly name: string
+ /**
+ * List available skill candidates for the current lookup context. Provider
+ * plugins register synchronously during `apply()`; remote initialization,
+ * authentication, and discovery are awaited inside this method. Implementations
+ * should settle promptly when `options.signal` aborts.
+ * @param options - lookup options; `cwd` selects workspace-sensitive skills and `signal` cancels work.
+ * @returns provider candidates with precedence ranks and opaque locators.
+ */
readonly list: (options: SkillLookupOptions) => Promise
+ /**
+ * Load a complete skill body for a previously listed candidate.
+ * @param candidate - the winning candidate originally returned by this provider.
+ * @param options - lookup options; `cwd` selects workspace-sensitive skills and `signal` cancels work.
+ * @returns the full skill body, or `undefined` if it is no longer loadable.
+ */
readonly get: (candidate: SkillCandidate, options: SkillLookupOptions) => Promise
}
```
@@ -39,6 +55,7 @@ interface SkillProvider {
skill 名称为 kebab-case(`^[a-z0-9]+(?:-[a-z0-9]+)*$`)。本地提供方接受目录包(`/SKILL.md`)和扁平 Markdown 文件(`.md`)。嵌套递归的 `**/SKILL.md` 发现有意不在 v1 范围内。
```ts type-equiv
+/** Origin bucket for a skill contribution. The value is prompt-visible metadata, not precedence by itself. */
type SkillSource = 'project-dsh' | 'project-agents' | 'runtime' | 'user-dsh' | 'user-agents' | 'custom' | (string & {})
```
@@ -47,13 +64,21 @@ type SkillSource = 'project-dsh' | 'project-agents' | 'runtime' | 'user-dsh' | '
`SkillSummary` 是注册表中可供模型调用的摘要形状。消费方自行选择渲染哪些字段;会话目录仅使用 `name` 和 `description`,从不使用 body 或绝对文件路径。`disableModelInvocation` 将 skill 从模型列表中隐藏,但允许受信代码按名称加载。
```ts type-equiv
+/** Model-visible skill metadata returned by `ctx.skills.list()` and rendered into request guidance. */
interface SkillSummary {
+ /** Kebab-case identifier used with the `skill` tool. */
readonly name: string
+ /** Short routing description shown to the model. */
readonly description: string
+ /** Optional extra routing guidance shown to the model. */
readonly whenToUse?: string
+ /** Whether the skill is hidden from model listings while remaining loadable by trusted callers. */
readonly disableModelInvocation?: boolean
+ /** Discovery source that produced this winning skill. */
readonly source: SkillSource
+ /** Provider that owns this skill body. */
readonly provider: string
+ /** Provider-specific base for relative resources. */
readonly resourceBase?: SkillResourceBase
}
```
@@ -61,10 +86,15 @@ interface SkillSummary {
`SkillCandidate` 是提供方到注册表的形状。`locator` 是提供方的不透明状态;注册表只存储它并在调用获胜提供方的 `get()` 时传回。
```ts type-equiv
+/** Provider catalog entry used by the registry to merge and later load skills. */
interface SkillCandidate extends SkillSummary {
+ /** Lower ranks win duplicate skill names before provider registration order is considered. */
readonly rank: number
+ /** Opaque provider-owned handle passed back to `provider.get()`. */
readonly locator: unknown
+ /** Absolute file path when the provider has one. */
readonly path?: string
+ /** Parsed optional metadata object from provider-specific skill frontmatter. */
readonly metadata?: Readonly>
}
```
@@ -72,6 +102,7 @@ interface SkillCandidate extends SkillSummary {
`SkillDefinition` 是 `ctx.skills.get()` 返回的完整解析结果,供 `skill` 工具使用。`resourceBase` 告知工具如何为本地、URL 或提供方管理的 skill 渲染相对资源引导。
```ts type-equiv
+/** Optional provider-specific base used by loaded skill bodies to resolve relative resources. */
type SkillResourceBase =
| { readonly kind: 'directory'; readonly path: string }
| { readonly kind: 'url'; readonly url: string }
@@ -79,9 +110,13 @@ type SkillResourceBase =
```
```ts type-equiv
+/** Complete parsed skill definition, including the body loaded by `ctx.skills.get()`. */
interface SkillDefinition extends SkillSummary {
+ /** Markdown instruction body after any provider-specific metadata removal. */
readonly content: string
+ /** Absolute file path when the skill came from disk. */
readonly path?: string
+ /** Parsed optional metadata object from frontmatter. */
readonly metadata?: Readonly>
}
```
@@ -89,9 +124,8 @@ interface SkillDefinition extends SkillSummary {
运行时 skill 使用相同的完整形状,参与相同的先到先得收集顺序。返回的 disposer 移除该贡献并使发现缓存失效。
```ts type-equiv
-type SkillRegistration = Omit & {
- readonly provider?: string
-}
+/** Runtime skill contribution accepted by `ctx.skills.register()`. */
+type SkillRegistration = Omit & { readonly provider?: string }
```
## 查找与配置
@@ -99,8 +133,11 @@ type SkillRegistration = Omit & {
skill 查找对 cwd 敏感,因为提供方可能暴露工作区本地的 skill;可选的 signal 为调用方取消提供方的工作。提供方接收与缓存标识和加载相同的只读选项对象。取消在目录选择前后(包括缓存命中时)都会检查,并与发现和完整定义加载竞争。如果找不到 git root,本地提供方将所提供的 cwd 本身视为项目根目录。
```ts type-equiv
+/** Caller context used for cwd-sensitive and abortable provider work. */
interface SkillLookupOptions {
+ /** Workspace selector for the current lookup. */
readonly cwd?: string | undefined
+ /** Abort discovery or loading work for the current caller. */
readonly signal?: AbortSignal | undefined
}
```
@@ -108,13 +145,15 @@ interface SkillLookupOptions {
注册表只拥有其发现缓存上限。本地提供方拥有文件系统根目录(`dshHome`、`agentsHome` 与 `customSkillDirs`)。消费方拥有其目录描述上限。
```ts type-equiv
+/** Skill registry configuration. */
interface Config {
+ /** Maximum number of completed cwd/provider catalogs kept in memory. */
readonly collectCacheMaxEntries?: number
}
```
## 会话目录与工具契约
-`dsh-tool-skill` 通过 `agent/session-prefix` 贡献一条 user-role 的 ``。目录包含排序后的 skill `name` 和经过规范化、XML 转义的 `description`;不包含 body、路径、来源、提供方和路由提示。前缀发现通过 `SkillLookupOptions` 转发调用方的 abort signal。`catalogDescriptionMaxLength` 是消费方配置的描述上限,默认值 `500`,整数最小值 `3`。其仅请求级别、记录于 header 的生命周期由 [session-prefix RFC](../rfc/implemented/feature/2026-07-07-session-prefix.md) 定义。
+`dsh-tool-skill` 通过 `agent/session-prefix` 贡献一条 user-role ``。目录只包含已排序的 skill `name` 和规范化、经 XML 转义的 `description`;不包含正文、路径、来源、提供方或路由提示。Prefix 发现通过 `SkillLookupOptions` 转发调用方的 abort signal。`catalogDescriptionMaxLength` 是消费方用于 description 上限的配置,默认值为 `500`,整数最小值为 `3`。其仅用于请求、记录在 header 中的生命周期由 [session-prefix Agent Note(agent 决策记录)](../../.agents/notes/implemented/feature/2026-07-07-session-prefix.md)定义。
面向模型的 `skill({ name })` 工具校验 kebab-case 名称,为调用方 agent 的 cwd 加载完整定义,将未解析的 skill 报告为 unknown 或 no longer available,拒绝 `disableModelInvocation` 的 skill,并返回包含 ``、`` 和 `` 的工具结果。`resourceBase` 仅按需解析显式引用的脚本、参考资料和资产;加载结果不枚举 skill 目录。工具结果是模型获取完整指令的可见路径。
diff --git a/docs/core-data-structures/subagent.i18n.yaml b/docs/core-data-structures/subagent.i18n.yaml
index ed154e096c..f7cf2d81de 100644
--- a/docs/core-data-structures/subagent.i18n.yaml
+++ b/docs/core-data-structures/subagent.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-subagent.md: eb9160abaee26969aecdc533fb9fd56fae18b7fa
-subagent.zh.md: b6a6bfbe61f5d2d3e0eb3bdc3aabed4b8b89317f
+subagent.md: 97d6862c10a0757c41472f207f857c25f3f5d50f
+subagent.zh.md: 1e88562aed99122750e9d137cb0b722d4c38c36b
diff --git a/docs/core-data-structures/subagent.zh.md b/docs/core-data-structures/subagent.zh.md
index b6a6bfbe61..1e88562aed 100644
--- a/docs/core-data-structures/subagent.zh.md
+++ b/docs/core-data-structures/subagent.zh.md
@@ -4,7 +4,7 @@
subagent seam:一个 agent(智能体)将工作委派给子 agent。与 [bash](bash.md) 一样,它是**一项可选能力**,不属于 agent loop(智能体循环)主干,因此其词汇定义在此而非 [core.md](core.md) 中。但它在一个维度上与其他所有 seam 不同:**同一上下文中可共存多个提供方实现**,按名称注册(`ctx.subagents`),而 bash 只允许一个执行器。注册表的形状参照 [LLM 适配器注册表](llm-streaming.md),而非单服务的 bash 执行器。
-接口:[dsh-subagent](../../packages/subagent/subagent)(`ctx.subagents` + 下文词汇)。实现为兄弟包(`dsh-subagent-spawn`、`-fork`、`-acp`);面向模型的消费方是 [dsh-tool-subagent](../../packages/subagent/tool-subagent)。提案与设计动机见 [subagent RFC](../rfc/implemented/feature/2026-06-21-subagent-capability-seam.md)。
+接口:[dsh-subagent](../../packages/subagent/subagent)(`ctx.subagents` + 下文词汇)。实现为兄弟包(`dsh-subagent-spawn`、`-fork`、`-acp`);面向模型的消费方是 [dsh-tool-subagent](../../packages/subagent/tool-subagent)。提案与设计理由见 [subagent Agent Note(agent 决策记录)](../../.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.md)。
源码:[`packages/subagent/subagent/src/types.ts`](../../packages/subagent/subagent/src/types.ts)
@@ -13,10 +13,22 @@ subagent seam:一个 agent(智能体)将工作委派给子 agent。与 [ba
提供方通过一个静态描述符公布其**启动时**特性,服务在 run 存在之前即行检查;如果请求依赖提供方不具备的特性,会被大声拒绝(`SubagentError('UNSUPPORTED_CAPABILITY')`),绝不会被接受后静默忽略。**运行时**特性(steering(中途引导)、resume)则是 [`SubagentRun`](#a-live-run-subagentrun) 上的可选方法——方法的存在即为能力,TypeScript 的类型收窄即为发现机制。
```ts type-equiv
+/**
+ * Which START-TIME features a provider supports. Checked by the service before delegating to
+ * {@link SubagentProvider.start}: a request that needs a capability the chosen provider lacks
+ * is rejected with a typed error rather than accepted-then-ignored (the "fail loud, no silent
+ * degradation" rule). These static flags cover features needed before a run exists; runtime
+ * capabilities such as steering and resume are optional {@link SubagentRun} methods whose presence
+ * is the capability.
+ */
interface SubagentCapabilities {
+ /** Honor {@link SubagentStartRequest.outputSchema} (structured final output). */
readonly outputSchema: boolean
+ /** Enforce {@link SubagentStartRequest.maxDepth} (recursion cap). */
readonly depthLimit: boolean
+ /** Enforce {@link SubagentStartRequest.toolFilter} (child tool scoping). */
readonly toolFilter: boolean
+ /** Honor {@link SubagentStartRequest.persona} (a per-child persona). */
readonly persona: boolean
}
```
@@ -26,28 +38,89 @@ interface SubagentCapabilities {
工具层根据模型输入和自身配置构建此请求;服务在 `start` 之前针对指定提供方进行校验。必填的 `parent` 提供会话 cwd、谱系与委派深度。可选的 output schema、depth、tool filter 和 persona 需要对应的能力 flag 匹配。不支持的 schema 在启动时即失败;进程内后端将 filter 和 persona 的作用域限定在子 agent 创建阶段,并通过强制 capture tool 实现所支持的 object-rooted schema。
```ts type-equiv
+/**
+ * What a caller asks for when starting a subagent. The tool layer builds this
+ * from the model's `{ description, prompt }` plus its own config; the service
+ * validates {@link SubagentCapabilities} against the named provider, then
+ * passes it to {@link SubagentProvider.start}.
+ */
interface SubagentStartRequest {
+ /** The task/prompt for the child agent (a user message in the child session). */
readonly prompt: ContentBlock[]
+ /**
+ * The spawning ("parent") agent — the one whose tool call started this
+ * subagent. REQUIRED: in-process backends read `parent.session.header` for
+ * the working directory, the `parentSession` lineage to stamp on the child,
+ * and the parent's delegation depth. The out-of-process backend (ACP) reads
+ * exactly one field — the session header's cwd, the child's workspace when
+ * no deployment `cwd` override is configured; nothing else crosses the
+ * process boundary.
+ */
readonly parent: Agent
+ /**
+ * Cancellation signal from the spawning context (the tool's `exec.signal`).
+ * This is the canonical cancellation channel both before and after startup:
+ * a provider rejects `start()` after cleaning partial resources when it
+ * fires before publication, and cancels a published child when it fires
+ * afterward.
+ */
readonly signal: AbortSignal
+ /** Per-child agent options (model and plugin-defined extension fields). */
readonly agentOptions?: AgentOptions
+ /**
+ * Object-rooted JSON Schema within `assertSupportedOutputSchema`'s enforced subset. Start rejects
+ * unsupported schemas or providers without the capability. Data must be plain host-realm JSON;
+ * a successful child returns the matching value as {@link SubagentResult.structured}.
+ */
readonly outputSchema?: StructuredOutputSchema
+ /**
+ * Optional absolute delegation-depth cap for the child being started: its
+ * computed depth must be less than or equal to this non-negative safe
+ * integer. Requires {@link SubagentCapabilities.depthLimit}; rejected at
+ * start otherwise.
+ */
readonly maxDepth?: number
+ /**
+ * Optional child tool scoping. Requires {@link SubagentCapabilities.toolFilter};
+ * rejected at start otherwise. In-process backends apply it as a scoped
+ * `tools.restrict()` in the child's creation window: the named tools vanish
+ * from the child's prompt AND refuse to execute (one visibility), with loud
+ * unknown-name validation.
+ */
readonly toolFilter?: ToolRestriction
+ /**
+ * Optional per-child persona. Requires {@link SubagentCapabilities.persona};
+ * rejected at start otherwise. In-process backends register it as a scoped
+ * `deployment:persona` section on the child, SHADOWING the deployment's
+ * persona for this child alone — same template semantics as the deployment
+ * persona (strict `{{…}}` interpolation against the registered variables).
+ */
readonly persona?: string
}
```
-`signal` 是就绪前后唯一的取消通道。[subagent 组合控制 RFC](../rfc/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.md) 负责 persona、运行时全局工具过滤、绝对深度以及「可见性而非权限」的设计理由。
+`signal` 是就绪前后唯一的取消通道。[subagent 组合控制 Agent Note](../../.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.md)规定 persona、live 全局工具过滤、绝对深度以及「可见性而非权限」的设计理由。
## 终态结果:`SubagentResult`
一次 run 的最终产出,由 `SubagentRun.result` resolve。`structured` 仅在请求了 `outputSchema` 且成功满足时才存在;请求 schema 不保证一定能得到它,当子 agent 失败或结束时未产出有效 capture 时,提供方可能返回 `stopReason: 'error'`。非 `completed` 的 `stopReason` 意味着 `output` 可能不完整——消费方将其映射为 `isError` 的工具结果,而非将部分输出报告为成功。
```ts type-equiv
+/**
+ * The terminal outcome of a subagent run, resolved by {@link SubagentRun.result}.
+ */
interface SubagentResult {
+ /** The child's final assistant output (the last assistant message's content). */
readonly output: ContentBlock[]
+ /**
+ * The structured result after a requested `outputSchema` was successfully
+ * satisfied. Requesting a schema does not guarantee presence: a provider can
+ * end with `stopReason: 'error'` when the child fails or finishes without a
+ * valid capture. Shape is validated against the request schema by the
+ * provider; `unknown` here because the seam is schema-agnostic.
+ */
readonly structured?: unknown
+ /** Why the run ended. A non-`completed` reason means `output` may be partial. */
readonly stopReason: SubagentStopReason
}
```
@@ -55,11 +128,22 @@ interface SubagentResult {
`SubagentStopReason` 是一个[可合并扩展的派生联合类型](core.md#the-map--derived-union-pattern)——后端可以添加变体,因此消费方应对已知 case 分支处理,将未知的终态原因视为失败:
```ts type-equiv
+/**
+ * Why a subagent run ended. Merge-extensible (a backend may add variants);
+ * consumers branch on the known cases and fall through `default`. The known
+ * cases mirror the harness turn-end vocabulary so the tool layer can map a
+ * non-`completed` result to an `isError` tool result.
+ */
interface SubagentStopReasonMap {
+ /** The child finished its turn normally. */
completed: 'completed'
+ /** The run was cancelled by its request signal or by disposal. */
aborted: 'aborted'
+ /** The child failed (model error, transport error). */
error: 'error'
+ /** The child hit its token ceiling before finishing. */
'max-tokens': 'max-tokens'
+ /** The child declined the task. */
refusal: 'refusal'
}
```
@@ -71,33 +155,94 @@ interface SubagentStopReasonMap {
`SubagentRun` 是消费方持有的、指向一个就绪子 agent 的句柄。消费方 await `result` 并始终 dispose(资源释放)该 run,直至其完全停稳。子 agent 失败时以非 completed 的 stop reason resolve;只有不可表示的基础设施故障才会 reject。可选的 `sendMessage` 和 `resume` 方法通过自身的存在来公布运行时能力。
```ts type-equiv
+/**
+ * Child handle returned only after readiness. Consumers await {@link result} and must always
+ * {@link dispose} to cancel remaining work and reach quiescence. Optional methods are runtime
+ * capability discovery; narrow their presence before calling.
+ */
interface SubagentRun {
- readonly id: AgentId
+ /**
+ * Parent-scoped run id. For a local run, this MUST equal the published child
+ * session id, whose `parentSession` records `request.parent.session.id`; a
+ * remote provider mints an id unique in the parent namespace.
+ */
+ readonly id: SessionId
+ /**
+ * The exact published in-process child, or `undefined` for a remote run.
+ * When present, its id is {@link id}; the provider retains no ownership
+ * implication beyond the run's ordinary {@link dispose} contract.
+ */
+ readonly localAgent: Agent | undefined
+ /**
+ * Resolves with the child's terminal {@link SubagentResult} when the run
+ * settles. Does NOT reject on a child-level failure — a model/transport
+ * failure resolves with `stopReason: 'error'` so the consumer maps it to an
+ * `isError` tool result. Rejects only on an infrastructure fault the seam
+ * cannot represent as a stop reason.
+ */
readonly result: Promise
+ /**
+ * Cancel remaining work, reach child quiescence, and release the run's
+ * resources (in-process: dispose the owned agent and remove its session;
+ * ACP: kill and reap the subprocess). Idempotent.
+ */
dispose(): Promise
+ /**
+ * OPTIONAL (steering capability): send additional content to the running
+ * child between steps. Present only on providers that support live steering.
+ */
sendMessage?(content: ContentBlock[]): void
+ /**
+ * OPTIONAL (resume capability): send a follow-up task to a settled child,
+ * continuing its session, and return a fresh run for the continuation.
+ */
resume?(content: ContentBlock[]): Promise
}
```
+本地 run 必须在 `start()` fulfill 前发布一个普通子 agent/session,将该子 session id 作为 `SubagentRun.id` 返回,以 `localAgent` 暴露确切子 agent,并在子 agent 的 `parentSession` header 中记录 `request.parent.session.id`。运行时所有权可以把子 agent 放在 parent、提供方或 root 作用域下。远程提供方则返回 parent 作用域的生命周期 id 与 `localAgent: undefined`。
+
## 提供方 seam:`SubagentProvider`
每个提供方是一个具名的子 agent 传输层,多个提供方可以共存。服务在 `start()` 之前校验请求的启动时能力。`inheritsParentContext` 仅描述对话种子注入(`fork`:true;`spawn` 和 `acp`:false),使消费方能生成准确的面向模型的措辞,而不暗示继承了工具、服务或权限。
```ts type-equiv
+/**
+ * A subagent backend: one transport for running a child agent (in-process
+ * spawn/fork, ACP to another process, …). Implementations register under a
+ * unique name via {@link SubagentService.registerProvider}; multiple providers
+ * coexist in one context (unlike the single-implementation bash seam). The
+ * Providers are trusted same-process implementations; callers treat their
+ * descriptors and returned values as borrowed immutable data.
+ */
interface SubagentProvider {
+ /** Unique registry name (e.g. `spawn`, `fork`, `acp`). */
readonly name: string
+ /** The start-time features this provider supports (see {@link SubagentCapabilities}). */
readonly capabilities: SubagentCapabilities
+ /**
+ * Whether the child sees the parent's completed-turn prefix. This is descriptive, not a
+ * service-validated start capability: the model-facing tool derives truthful wording from it.
+ * It says nothing about tool registration, injected services, or authority inheritance.
+ */
readonly inheritsParentContext: boolean
+ /**
+ * Establish a child and return its handle only after publication. The
+ * service has already validated that every requested start-time capability
+ * is supported, so an implementation may assume e.g. `request.maxDepth` is
+ * honorable when present. If setup fails or `request.signal` aborts before
+ * fulfillment, the provider owns and cleans all partial resources before this
+ * promise rejects. Ownership transfers to the caller only on fulfillment.
+ */
start(request: SubagentStartRequest): Promise
}
```
-`start()` 仅在 run 就绪时 fulfill。服务观察其 result、发出 `subagent/start`,并返回同一个 run;rejection 意味着提供方已自行清理,不发出生命周期配对事件。进程内子 agent 可通过 `ctx.agents` 发现,远程子 agent 则不必如此。`subagent/end` 报告最终输出或基础设施故障。两个事件均为仅观察事件;每个监听器异常都会被独立隔离。
+`start()` 仅在 run 就绪时 fulfill。服务铸造唯一 `runId`,从提供方的确切 `localAgent` 快照 `local`,观察结果,emit `subagent/start`,并返回同一个 run;rejection 意味着提供方已清理,且不会 emit 生命周期事件对。配对的 `subagent/end` 携带相同标识与最终输出或基础设施失败。两个事件都仅用于观察,每个 listener 异常都会被独立隔离。
## 进程内后端:深度与种子
spawn 和 fork 后端通过 `parent.ctx` 创建一个普通 agent,将取消信号传入核心创建流程,并通过 `AgentHandle` 进行 dispose。移除提供方会阻止新的 start,但不会撤销已接受的 run。每个子 agent 获得一个新的扁平作用域,而非继承父级注册。深度与 fork 种子注入复用既有的 agent 和会话词汇:
-- **委派深度**是一个可合并扩展的 `AgentOptions.subagentDepth` 字段(顶层 agent 为 `0`,子 agent 为 parent + 1)。只有 `undefined` 表示顶层;所有已存储的值必须是非负安全整数。该字段归 seam 所有——循环既不设置也不读取它——因此嵌套 spawn 会校验父级的已存储深度,拒绝超出安全整数域的派生子深度,并在定义了绝对 `request.maxDepth` 上限时将其施加于子 agent。
+- **委派深度**由持久 `SessionHeader.delegationDepth` 与可合并扩展的运行时字段 `AgentOptions.subagentDepth` 共同表示;缺失表示顶层深度为零,存在的较大值具有权威性。两个字段都归该 seam 所有——循环既不设置也不读取它们——因此进程内子 agent 会持久保存 parent 深度 + 1,resume 无法降低深度,而且每次 start 都会拒绝超出安全整数域、或高于已定义绝对 `request.maxDepth` 上限的派生深度。
- **Fork 种子注入**使用 `CreateAgentOptions.seed`(一个 `SessionEvent[]` 前缀,经由 `AgentLoop.createAgent` → `ctx.sessions.prepare({ seed })` 传递,与 `resume` 使用的原语相同)。fork 后端传入父级日志的一段*平衡的已完成轮次前缀*——父级事件直到并包括其最后一个 `turn/end`——因此种子从 0 连续,[invariants](../../packages/support/invariants) 回放可以接受它(进行中的、未平衡的轮次被排除在外)。
diff --git a/docs/core-data-structures/system-prompt.i18n.yaml b/docs/core-data-structures/system-prompt.i18n.yaml
index f2918af35f..8e68fc099b 100644
--- a/docs/core-data-structures/system-prompt.i18n.yaml
+++ b/docs/core-data-structures/system-prompt.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-system-prompt.md: 175f2af407e5c39a24f0f8f8e4e664063b897ead
-system-prompt.zh.md: 8827ac0b915915f716643e0a9e04edaacedbc868
+system-prompt.md: 63a750c74300b4353f132d3dae9da52a10631f23
+system-prompt.zh.md: 748e9e4406fe8ca1071aa87f5926bd043378ccdb
diff --git a/docs/core-data-structures/system-prompt.zh.md b/docs/core-data-structures/system-prompt.zh.md
index 8827ac0b91..748e9e4406 100644
--- a/docs/core-data-structures/system-prompt.zh.md
+++ b/docs/core-data-structures/system-prompt.zh.md
@@ -8,11 +8,18 @@
## 组装上下文
-`AssembleContext` 标识一次组装所解析的作用域层。它可通过合并扩展:`dsh-agent` 添加可选的活跃 `agent` 字段,`assembleContextFor(agent)` 同时设置该字段与 `scope`。
+`AssembleContext` 标识一次组装所解析的作用域 layer,并可携带该请求的显式控制 signal。它可合并扩展:`dsh-agent` 添加可选的 live `agent` 字段,`assembleContextFor(agent, signal)` 则一起设置这些显式字段。裸组装既没有 scope,也没有 signal。
```ts type-equiv
+/** Merge-extensible context for one prompt assembly. */
interface AssembleContext {
+ /**
+ * Scope whose providers and waterfall listeners participate. When absent,
+ * only global providers and subject-less listeners participate.
+ */
scope?: ScopeKey
+ /** Explicit control signal for the turn that requested this assembly, when any. */
+ signal?: AbortSignal
}
```
@@ -21,8 +28,11 @@ interface AssembleContext {
`ToolProviderResult.schemas` 是当前组装中对模型可见的工具集合。`knownNames` 是提供方在限制前的名称全集,用于区分「配置名拼写错误」与「已知工具在此作用域中被有意隐藏」。
```ts type-equiv
+/** Tool schemas visible in one assembly and their pre-restriction name set. */
interface ToolProviderResult {
+ /** The schemas this provider contributes to THIS assembly. */
readonly schemas: readonly ToolSchema[]
+ /** The pre-restriction name universe for config validation (defaults to `schemas`' names). */
readonly knownNames?: readonly string[]
}
```
@@ -32,9 +42,21 @@ interface ToolProviderResult {
`PromptSection` 是一份只读的同进程注册契约。其文本可以是静态的,也可以从当前组装上下文动态解析。
```ts type-equiv
+/** One contributed section of the system prompt (registry input). */
interface PromptSection {
+ /** Unique name — a duplicate registration throws (see {@link SystemPrompt.section}). */
readonly name: string
+ /**
+ * Sections are concatenated in ascending order. Convention: `-100` is the
+ * harness identity, `0` the deployment persona, tool guidance uses 100–199;
+ * other negative orders also render before the persona.
+ */
readonly order: number
+ /**
+ * Static text or a provider evaluated at each assembly with that assembly's
+ * {@link AssembleContext}. The text may reference `{{variable}}`s — they are
+ * interpolated later, by {@link renderPrompt}.
+ */
readonly text: string | ((context: AssembleContext) => string)
}
```
diff --git a/docs/core-data-structures/tools.i18n.yaml b/docs/core-data-structures/tools.i18n.yaml
index 7f55967dcb..2f09ee1e2d 100644
--- a/docs/core-data-structures/tools.i18n.yaml
+++ b/docs/core-data-structures/tools.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-tools.md: f8be67054cd81027d4b751329948a784fa4f0ed9
-tools.zh.md: 27066180bc3a3666e4ef5c789034adc0a82e05b8
+tools.md: ce14a37da33f89b8b90d6d8e70756f94e3d690dd
+tools.zh.md: 869480fc38688a15a8681648903e1a4a0959c79d
diff --git a/docs/core-data-structures/tools.zh.md b/docs/core-data-structures/tools.zh.md
index 27066180bc..869480fc38 100644
--- a/docs/core-data-structures/tools.zh.md
+++ b/docs/core-data-structures/tools.zh.md
@@ -8,11 +8,21 @@
## `ToolDefinition` — 一个已注册的工具
-一个 `ToolSchema`(面向模型的字段)加上 `execute` 函数和可选的 UI 展示器。注册表持有这些定义;agent loop(智能体循环)通过它们分派调用。注册表的 `schemas()` 通过显式白名单构建面向模型的 `ToolSchema[]`——`execute`/`presentCall`/`presentResult` 绝不能泄漏到模型请求中。
+由一个 `ToolSchema`(面向模型的字段)、`execute` 函数、仅供宿主使用的调度器元数据和可选 UI 展示函数组成。注册表持有这些定义,循环通过它们分派调用。注册表的 `schemas()` 通过显式允许列表构建面向模型的 `ToolSchema[]`;`execute`/`timeoutMs`/`isConcurrencySafe`/`presentCall`/`presentResult` 绝不能泄漏到模型请求中。
```ts type-equiv
+/** A registered tool: its schema plus the execution function. */
interface ToolDefinition extends ToolSchema {
- execute(args: unknown, exec: ToolExecution): Promise
+ /**
+ * Run one accepted call. Async work must observe or forward `exec.signal` and
+ * settle only after its owned work reaches quiescence. The registry preserves
+ * caller cancellation through around-dispatch signal replacement and does
+ * not abandon this promise, but it cannot hard-kill same-process code.
+ * @param args - losslessly snapshotted, frozen model arguments.
+ * @param exec - execution identity, cancellation signal, and context deferral.
+ * @returns model-facing content plus optional private presentation metadata.
+ */
+ execute(args: unknown, exec: ToolRunContext): Promise
/**
* Cooperative tool-call timeout budget in milliseconds. Omit for no deadline.
* Enforced by `@deepseek-ai/dsh-timeout-policy` (a `tools/execute` wrapper); it
@@ -21,6 +31,20 @@ interface ToolDefinition extends ToolSchema {
* cooperative implementation that can reach quiescence when the signal aborts.
*/
timeoutMs?: number
+ /**
+ * Pure synchronous classifier for overlap with sibling tool calls. Only
+ * `true` opts in; omission, exceptions, non-`true` returns, and invalid
+ * `defineTool` arguments are exclusive. This metadata is never model-visible.
+ *
+ * Opted-in executions must not mutate parent-owned state. Shared state must
+ * tolerate concurrent dispatch; recorder races are permitted only when they
+ * commute or fail closed. See the
+ * [parallel-tool-call Agent Note](../../../../.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md)
+ * for the full contract.
+ * @param args - parsed arguments; `defineTool` validates before calling.
+ * @returns Whether this call may join a parallel group.
+ */
+ isConcurrencySafe?(args: unknown): boolean
/**
* Optional: how to present the PENDING state of one call in a UI, derived from
* the call's `args` (parsed arguments, `unknown` — the tool validates/narrows
@@ -51,6 +75,7 @@ interface ToolDefinition extends ToolSchema {
源码:[`packages/core/tools/src/schema.ts`](../../packages/core/tools/src/schema.ts)
```ts type-equiv
+/** One schema-spec property entry. */
interface SchemaProp {
type: SchemaType
/** Per-property required flag (NOT the JSON Schema top-level required array). */
@@ -59,7 +84,10 @@ interface SchemaProp {
description?: string
/** Enum of allowed values (strings only). */
enum?: string[]
- /** Default value. */
+ /**
+ * Model-visible JSON Schema default annotation. Validation does not apply it;
+ * dynamic tool mounts may supply it even though first-party definitions do not.
+ */
default?: unknown
/** Nested properties for type: 'object'. */
properties?: SchemaSpec
@@ -69,12 +97,29 @@ interface SchemaProp {
```
```ts type-equiv
+/**
+ * The author-facing parameter schema: a shallow map of property name to
+ * {@link SchemaProp}. Required-ness is a per-property boolean (`required:
+ * true`), not a separate array.
+ */
type SchemaSpec = Record
```
`SchemaType` 是原始联合类型 `'string' | 'number' | 'boolean' | 'object' | 'array'`。`InferArgs` 将一个 `SchemaSpec` 映射为 TS 参数类型——`required: true` 的属性成为必选键,其余为真正的可选:
```ts type-equiv
+/**
+ * Infer the TS argument type for a complete {@link SchemaSpec}.
+ *
+ * Properties marked `required: true` are required keys; all others are
+ * genuinely optional keys (`?`), so callers may omit them entirely.
+ *
+ * Example:
+ * ```ts
+ * type Args = InferArgs<{ path: { type: 'string'; required: true }; limit: { type: 'number' } }>
+ * // → { path: string; limit?: number }
+ * ```
+ */
type InferArgs = Simplify<
& { [K in RequiredKeys]: InferPropValue }
& { [K in Exclude>]?: InferPropValue }
@@ -90,54 +135,126 @@ type InferArgs = Simplify<
`ToolRestriction` 仅作用于实时的部署全局工具层。注册表将 readonly 名称编译为私有集合,对多个限制取交集,再叠加作用域本地工具。仅 deny 的过滤器允许后续未列出的全局工具通过,而 allow 列表则排除它们。
```ts type-equiv
+/**
+ * Per-scope filter over global tools. Restrictions intersect and do not affect
+ * scoped registrations or the reserved Code Mode transport.
+ */
interface ToolRestriction {
+ /** Global tool names that stay visible; everything else is removed. */
readonly allow?: readonly string[]
+ /** Global tool names removed from visibility. */
readonly deny?: readonly string[]
}
```
## 执行:可扩展的 waterfall(瀑布式事件)加单调策略
-`ctx.tools.execute()` 接收调用方拥有的 `ToolExecutionInput`,将其解析后的 JSON 参数一次性物化为流水线拥有的 `ToolExecution`,然后依次通过 `tools/pre-execute`(可重排的 allow/deny/ask waterfall)→ 已注册的单调 guard → `tools/execute`(around-dispatch 包装层)→ `tools/post-execute`(检查/替换结果)→ `tools/result`(不可变的权威结果)。最终产出为 `ToolExecutionResult`。
+`ctx.tools.execute()` 接受由调用方拥有且包含必需 readonly `signal` 的 `ToolExecutionInput`,将其解析后的 JSON 参数一次性物化为流水线拥有的 `ToolExecution`,然后让调用依次经过 `tools/pre-execute`(可重排的 allow/deny/ask waterfall)→ 已注册的单调 guard → `tools/execute`(环绕分派包装层)→ `tools/post-execute`(检查/替换结果)→ `tools/result`(不可变的权威结果)。只有 `tools/execute` 视图可以替换必需的 signal。最终产出为 `ToolExecutionResult`。
```ts type-equiv
+/** Opaque call identity that permits correlation without exposing mutable execution state. */
type ToolExecutionToken = symbol & { readonly [toolExecutionTokenBrand]: true }
```
```ts type-equiv
+/**
+ * Caller-supplied description of one tool call. {@link ToolRegistry.execute}
+ * adds the registry-owned token to form a pipeline {@link ToolExecution};
+ * callers do not choose that token.
+ */
interface ToolExecutionInput {
readonly callId: CallId
readonly name: string
- /** Parsed JSON arguments (unknown — tools validate their own input). */
+ /** Losslessly JSON-serializable parsed arguments (tools validate their own schema). */
readonly arguments: unknown
/** The agent on whose behalf the call runs (set by the agent loop). */
readonly agent?: Agent
/**
* Opaque token of the enclosing transport execution, when one exists. Code
* Mode sets this on SDK sub-dispatches so commit-style observers can wait for
- * the outer `run_code` outcome without receiving its live mutable execution.
- */
+ * the outer `run_code` outcome without receiving its live mutable execution.
+ */
readonly parent?: ToolExecutionToken
- signal?: AbortSignal
+ /** Required caller-owned cancellation for this invocation. */
+ readonly signal: AbortSignal
}
```
+工具函数体接收运行时扩展。`deferContext()` 是组合工具的通道:它记录嵌套分派产生的上下文,而不会在外层调用尚未结束时注入这些上下文。
+
```ts type-equiv
+/**
+ * Runtime context handed to a tool implementation after the registry has
+ * accepted a {@link ToolExecution}. A composite tool uses
+ * {@link deferContext} to ferry context produced by nested dispatches back to
+ * the outer result; the loop appends it only after the outer `tool/result`.
+ */
+interface ToolRunContext extends ToolExecution {
+ /**
+ * Defer one nested-dispatch context until this tool's final result reaches
+ * the agent loop. Contexts retain their individual source and metadata and
+ * are emitted in call order.
+ */
+ deferContext(context: HookContext): void
+}
+```
+
+agent loop(智能体循环)向注册表查询每个待处理调用的执行模式,并据此形成独占屏障和滚动池并行执行:
+
+```ts type-equiv
+/**
+ * Scheduling mode for one pending call. `parallel` may overlap with siblings;
+ * `exclusive` runs alone and forms an ordering barrier.
+ */
+type ToolExecutionMode =
+ | { kind: 'parallel' }
+ | { kind: 'exclusive' }
+```
+
+```ts type-equiv
+/**
+ * One pending tool call inside the registry pipeline. Parsed arguments cross
+ * one lossless-JSON materialization boundary before policy and are deep-frozen;
+ * call identity, the caller signal, and the registry-assigned {@link token} are
+ * readonly. The registry freezes the complete object before `tools/result`
+ * observers run.
+ */
interface ToolExecution extends ToolExecutionInput {
/** Registry-assigned identity shared with nested calls only as their opaque `parent` token. */
readonly token: ToolExecutionToken
}
```
-`ToolExecutionToken` 是一个不透明的运行时 `Symbol`,仅用于身份比较。在策略执行之前,`execute()` 物化并冻结参数、拒绝非 JSON 输入、分配 token。身份字段和可选的 parent token 保持 readonly;只有 `signal` 可以在分派前后变化。最终观察者接收到的是冻结的执行身份。
+```ts type-equiv
+/**
+ * Around-dispatch view of a {@link ToolExecution}. A `tools/execute` wrapper
+ * may replace the signal for its delegated lifetime, but it cannot remove it.
+ * The registry fuses every replacement with the captured caller signal.
+ */
+interface ToolDispatchExecution extends Omit {
+ /** Cancellation signal visible to the next wrapper or tool body. */
+ signal: AbortSignal
+}
+```
+
+`ToolExecutionToken` 是不透明的运行时 `Symbol`,仅用于身份比较。策略执行前,`execute()` 会物化并冻结参数、拒绝非 JSON 输入并分配 token。身份字段、调用方必需的 signal 和可选的 parent token 均保持 readonly。`ToolDispatchExecution` 包装层可以替换 signal 但不能移除;注册表会在调用工具函数体前重新融合调用方的 signal。最终观察者接收冻结的执行身份。
`ToolGuard` 是感知作用域的最终预分派策略。其形状有意不包含 allow 结果:`undefined` 保留 waterfall 的决策,而返回的 reason 只能缩减权限,因此后续监听器无法撤销它。
```ts type-equiv
+/**
+ * A monotonic execution guard evaluated after every `tools/pre-execute`
+ * listener and before the tool body. Returning a reason denies the call;
+ * returning `undefined` leaves it unchanged. Because guards have no allow
+ * result, listener ordering cannot turn a denial back into permission.
+ * @param execution - the identity-protected call after extensible pre-execute policy completed.
+ * @returns a final denial reason, or `undefined` to leave the call allowed.
+ */
type ToolGuard = (execution: Readonly) => string | undefined
```
```ts type-equiv
+/** The outcome of one tool call. */
interface ToolExecutionResult {
content: ContentBlock[]
isError: boolean
@@ -148,16 +265,10 @@ interface ToolExecutionResult {
*/
error?: ToolErrorInfo
/**
- * Extra model-facing context a `tools/post-execute` listener attached for the
- * NEXT request (Claude Code's PostToolUse `additionalContext`). It is NOT part
- * of this call's `content` — `content`/`feedback` shape the tool RESULT, but
- * `additionalContext` is a SEPARATE `context/message`. A step can carry
- * multiple tool calls, so the loop BUFFERS every call's `additionalContext`
- * and appends them only AFTER all `tool/result`s for the step, keeping
- * tool-call/result adjacency intact. Carried on the result purely to ferry it
- * from `execute()` up to the loop's per-step buffer.
+ * Model-facing context for the next request, separate from this tool result. The loop
+ * accepts it into the active-batch FIFO, then appends after recorded results even if interrupted.
*/
- additionalContext?: HookContext
+ additionalContexts?: HookContext[]
/**
* The tool-private presentation payload from a successful `execute` (the object
* return form). Threaded onto the `tool/result` session event and back into
@@ -175,6 +286,12 @@ interface ToolExecutionResult {
每个拦截 waterfall 返回一个类型化的 **Decision**(与 `agent/*` seam 共享的惯用模式)。`tools/pre-execute` 监听器接收 `(exec, next)` 并返回 `PreToolDecision`;`tools/execute` 包装层返回 `ToolExecutionResult`;`tools/post-execute` 监听器接收 `(exec, result, next)` 并返回 `PostToolDecision`:
```ts type-equiv
+/**
+ * Pre-dispatch decision. `allow` runs the call; `deny` materializes an error;
+ * `ask` runs only after an approval service returns `allowed-once` and otherwise
+ * denies. Input rewriting is excluded because arguments are already logged and
+ * presented.
+ */
type PreToolDecision =
| { kind: 'allow' }
| { kind: 'deny'; reason: string }
@@ -182,9 +299,13 @@ type PreToolDecision =
```
```ts type-equiv
+/**
+ * Post-dispatch decision: accept or replace content, attach context for the next
+ * request, or block by turning corrective feedback into an error result.
+ */
type PostToolDecision =
- | { kind: 'accept'; content?: ContentBlock[]; additionalContext?: HookContext }
- | { kind: 'block'; feedback: ContentBlock[]; additionalContext?: HookContext }
+ | { kind: 'accept'; content?: ContentBlock[]; additionalContexts?: HookContext[] }
+ | { kind: 'block'; feedback: ContentBlock[]; additionalContexts?: HookContext[] }
```
调用 `next()` 获取默认决策,或直接返回一个决策以短路。前置策略可以 deny 或 ask;只有 `allowed-once` 才继续执行,而未授权、缺少审批通道或服务、或无 agent 的请求都会变为拒绝。Guard 仍可施加最终拒绝。参数不可被改写,因为历史记录、审计、UI 和执行必须保持一致。
@@ -196,25 +317,41 @@ type PostToolDecision =
调用方用来向 subagent 要求机器可读结果的词汇(`SubagentStartRequest.outputSchema`,见 [subagent.md](subagent.md#the-start-request)),或工作流 `agent()` 调用使用的词汇。它有意不是完整的 JSON Schema:schema 原样传给模型作为强制工具的 `parameters`,产出的值由 `validateStructuredValue` 在客户端校验——因此每个被接受的关键字都必须是校验器实际执行的,`assertSupportedOutputSchema` 会大声拒绝其他任何内容(`OutputSchemaError`,列出所有违规项)。两个遍历器仅推理自有可枚举属性(JSON 不携带其他内容),并拒绝会有损序列化的非纯对象(`Date`、`Map`)。
```ts type-equiv
+/** The scalar values `enum`/`const` may carry (finite numbers only). */
type StructuredScalar = string | number | boolean | null
```
```ts type-equiv
+/** The `type` keywords the subset accepts. */
type StructuredSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null'
```
```ts type-equiv
+/**
+ * One node of the structured-output schema subset. Recursive via `properties`
+ * and `items`; see the module doc for the exact keyword semantics.
+ */
interface StructuredSchemaNode {
type: StructuredSchemaType
+ /** Nested property schemas (`type: 'object'` only). */
properties?: Record
+ /** Required property names; each must appear in `properties`. */
required?: string[]
+ /** `false` rejects undeclared keys; absent/`true` allows them (JSON Schema default). */
additionalProperties?: boolean
+ /** Item schema (`type: 'array'` only); absent ⇒ any JSON items. */
items?: StructuredSchemaNode
+ /** Allowed values (scalar types only). */
enum?: StructuredScalar[]
+ /** The single allowed value (scalar types only). */
const?: StructuredScalar
+ /** Annotation, ignored for validation. */
description?: string
+ /** Annotation, ignored for validation. */
title?: string
+ /** Annotation, ignored for validation (must still be JSON data). */
default?: unknown
+ /** Annotation, ignored for validation (must still be JSON data). */
examples?: unknown
}
```
@@ -222,6 +359,7 @@ interface StructuredSchemaNode {
schema 是一个以 object 为根的节点(`enum`/`const` 仅限标量;`description`/`title`/`default`/`examples` 是注解,允许但忽略,但仍要求为 JSON 数据——它们随协议传输):
```ts type-equiv
+/** A structured-output schema: an OBJECT-rooted {@link StructuredSchemaNode}. */
type StructuredOutputSchema = StructuredSchemaNode & { type: 'object' }
```
@@ -232,6 +370,6 @@ type StructuredOutputSchema = StructuredSchemaNode & { type: 'object' }
- `ToolCallView`(待执行):`{ card: 'generic', title, kind?, rawInput?, content?, locations? }`(默认卡片;`locations` 是 `{ path, line? }[]`,表示调用读取/修改的文件,供编辑器跟随)、`{ card: 'terminal', title, description?, cwd? }`(shell 命令→终端卡片)、或 `{ card: 'diff', title, diffs, locations? }`(文件创建/修改→行内 diff 卡片;`diffs` 是 `{ path, oldText, newText }[]`,新文件时 `oldText: null`)。
- `ToolResultView`(已完成):`{ card: 'generic', title?, content? }`、`{ card: 'terminal', title?, output?, exitCode?, signal? }`(捕获的运行输出 + 退出状态;有能力的 UI 显示退出状态标签,无能力的 UI 获得桥接层从 `output` 派生的围栏 ` ```console ` 回退)、或 `{ card: 'diff', title?, diffs }`(已完成的文件变更→要展示的变更,通常是从变更前后内容计算出带上下文行的已应用 hunk,或在没有前像时的整文件 diff——例如文件创建。`tool_call_update` 的内容会替换调用的内容,因此变更工具即使与调用时的片段重复也要返回此卡片,以防结果文本覆盖 diff)。
-`ToolCallKind`(`'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other'`)为 generic 卡片选择图标。`FileLocation`(`{ path, line? }`)和 `FileDiff`(`{ path, oldText, newText }`)是共享的文件卡片词汇。该设计固定在[渲染意图联合类型 RFC](../rfc/implemented/architecture/2026-07-02-tool-render-intent-union.md) 中;ACP 桥接层将 `diff` 卡片映射为 `{ type: 'diff' }` 内容块,将 `terminal` 卡片映射为 `_meta` 终端约定,并将文件卡片的标题相对于会话 cwd 做相对化处理。
+`ToolCallKind`(`'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other'`)用于为通用卡片选择图标。`FileLocation`(`{ path, line? }`)与 `FileDiff`(`{ path, oldText, newText }`)是共享的文件卡片词汇。该设计由[渲染意图联合类型 Agent Note(agent 决策记录)](../../.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.md)固定;ACP 桥接层将 `diff` 卡片映射为 `{ type: 'diff' }` 内容块,将 `terminal` 卡片映射为 `_meta` 终端约定,并根据会话 cwd 将文件卡片标题转换为相对路径。
-完整的展示字段文档见 [`packages/core/tools/src/presentation.ts`](../../packages/core/tools/src/presentation.ts)。bash 工具自身的 schema(`bash`/`bash_output`/`bash_kill`)及其驱动的执行器见 [bash.md](bash.md)。
+完整的展示字段文档见 [`packages/core/tools/src/presentation.ts`](../../packages/core/tools/src/presentation.ts)。`bash` schema 与执行器见 [bash.md](bash.md);通用后台控制见 [tasks.md](tasks.md)。
diff --git a/docs/core-data-structures/user-interaction.i18n.yaml b/docs/core-data-structures/user-interaction.i18n.yaml
index d0c0b33ce5..7a135fdf88 100644
--- a/docs/core-data-structures/user-interaction.i18n.yaml
+++ b/docs/core-data-structures/user-interaction.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-user-interaction.md: 47e0e26cd0a5201185dd252a882496456a9c3edd
-user-interaction.zh.md: e7d2f27b8729a7694008d1ae7e21bdccae6058dd
+user-interaction.md: c7684879c6b81d75e2737857279e68e30626bfa4
+user-interaction.zh.md: e1772fdd9427829027e108b38093c6c04c23f041
diff --git a/docs/core-data-structures/user-interaction.zh.md b/docs/core-data-structures/user-interaction.zh.md
index e7d2f27b87..e1772fdd94 100644
--- a/docs/core-data-structures/user-interaction.zh.md
+++ b/docs/core-data-structures/user-interaction.zh.md
@@ -2,7 +2,7 @@
[English](user-interaction.md) | 中文
-[dsh-user-interaction](../../packages/ui/user-interaction) 的用户交互 seam。它是提供方无关的词汇,工具或权限插件在需要人类回答后 agent(智能体)才能继续时使用这套词汇。UI 表面提供活跃的 `UserInteractionProvider`:`dsh-stdio-demo` 在 readline 中渲染问题,`dsh-acp` 将其映射为 ACP(Agent Client Protocol)表单征询。
+[dsh-user-interaction](../../packages/ui/user-interaction) 的用户交互 seam。它是工具或权限插件需要人类回答后 agent 才能继续时所使用的、提供方中立的词汇。UI surface 提供活跃的 `UserInteractionProvider`:`dsh-tui` 使用键盘驱动的 overlay,`dsh-acp` 则把问题映射为 ACP 表单 elicitation。
源码:[`packages/ui/user-interaction/src/index.ts`](../../packages/ui/user-interaction/src/index.ts)
@@ -11,6 +11,7 @@
`AskUserQuestionOption` 是可选择项的形状。`label` 是面向用户的选项文字,同时也是面向模型的选中值;`description` 是可选的 UI 帮助文本。
```ts type-equiv
+/** One selectable answer offered to the user. */
interface AskUserQuestionOption {
/** User-facing label. */
label: string
@@ -21,14 +22,17 @@ interface AskUserQuestionOption {
## 问题条目
-`AskUserQuestionItem` 是请求中的一个问题。模型提供一个稳定的 `id`,回答时原样回传,使批量问题可路由。
+`AskUserQuestionItem` 是请求中的一个问题。调用方提供稳定的 `id`,它会随答案原样返回,使批量问题仍可路由。可选的 `detail` 携带辅助文本;提供方会将其随问题渲染,但不会放入可选 option label。
```ts type-equiv
+/** One question in a user-interaction request. */
interface AskUserQuestionItem {
- /** Stable model-provided question id, echoed in the answer. */
+ /** Stable caller-provided question id, echoed in the answer. */
id: string
/** The question to display. */
question: string
+ /** Optional supporting detail rendered with the question but kept out of option labels. */
+ detail?: string
/** Optional short heading/group label. */
header?: string
/** Optional choices the UI can render as a menu. */
@@ -43,6 +47,7 @@ interface AskUserQuestionItem {
`AskUserQuestionRequest` 是跨包(package)的请求。`questions` 是数组,这样 UI 可以在一个流程中呈现相关提示,同时保持每个回答有稳定的 id。
```ts type-equiv
+/** Request for a human answer. */
interface AskUserQuestionRequest {
/** Questions to display. */
questions: AskUserQuestionItem[]
@@ -58,6 +63,7 @@ interface AskUserQuestionRequest {
提供方为每个已回答的问题 id 返回一条回答。`selected` 包含选中的选项标签,`custom` 在用户输入自由文本时携带「其他」回答。当 `custom` 存在时,`selected` 为空;自定义文本是对选中项的覆盖,而非补充。
```ts type-equiv
+/** Answer to one question. */
interface AskUserQuestionAnswerItem {
/** The answered question id. */
id: string
@@ -69,6 +75,7 @@ interface AskUserQuestionAnswerItem {
```
```ts type-equiv
+/** The human's answer. */
interface AskUserQuestionAnswer {
/** Structured answers keyed by question id. */
answers: AskUserQuestionAnswerItem[]
@@ -80,6 +87,7 @@ interface AskUserQuestionAnswer {
同一上下文中只能有一个活跃的提供方。提供方注册绑定到 effect,因此 HMR(热模块替换)或 dispose(资源释放)会移除当前活跃的 UI。
```ts type-equiv
+/** UI-side provider for user questions. */
interface UserInteractionProvider {
ask(request: AskUserQuestionRequest): Promise
}
@@ -90,6 +98,7 @@ interface UserInteractionProvider {
`UserInteractionError` 继承 `HarnessError`,因此 `ctx.tools.execute()` 会保留 `{ name, code }`,用于面向模型的工具失败,如 `EMPTY_QUESTIONS`、`NO_PROVIDER`、`ASK_ABORTED` 或 ACP 侧取消。
```ts type-equiv
+/** Stable error taxonomy for user-interaction failures. */
class UserInteractionError extends HarnessError {
constructor(message: string, code: string, options?: ErrorOptions) {
super(message, code, options)
diff --git a/docs/core-data-structures/web.i18n.yaml b/docs/core-data-structures/web.i18n.yaml
index 05d23f25a4..efcc7b3258 100644
--- a/docs/core-data-structures/web.i18n.yaml
+++ b/docs/core-data-structures/web.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-web.md: 74db18835df02ef233f78ad7fbfec5d9b26d58e6
-web.zh.md: c5b99b72bc9ce1be19ebcad5ffad61fa256e1509
+web.md: 20d07240c9d9fea2f1f5abbac810f349a3e81f9b
+web.zh.md: d4d9259db5c834349c1cf9c72ed5c74b0a02b32b
diff --git a/docs/core-data-structures/web.zh.md b/docs/core-data-structures/web.zh.md
index c5b99b72bc..d4d9259db5 100644
--- a/docs/core-data-structures/web.zh.md
+++ b/docs/core-data-structures/web.zh.md
@@ -2,7 +2,7 @@
[English](web.md) | 中文
-Web 访问 seam 是一个[能力 seam](../rfc/implemented/architecture/2026-06-24-web-capability-seam.md),在一个 `ctx.web` 服务上横跨**两项能力**(搜索与抓取),分布在多个包(package)中:接口([dsh-web](../../packages/web/web),`ctx.web` + 提供方注册表)、实现([dsh-web-search-exa](../../packages/web/web-search-exa)、[dsh-web-search-perplexity](../../packages/web/web-search-perplexity)、[dsh-web-search-deepseek](../../packages/web/web-search-deepseek)、[dsh-web-fetch-local](../../packages/web/web-fetch-local)),以及消费方([dsh-tool-web](../../packages/web/tool-web),`web_search`/`web_fetch` 工具 schema)。Web 是**一项可选能力**,不属于 agent loop(智能体循环)主干,因此其词汇定义在此,而非 [core.md](core.md)。更换搜索提供方不会改变模型发起查询的方式,更换抓取实现也不会改变模型请求 URL 的方式。
+Web 访问 seam 是一个[能力 seam](../../.agents/notes/implemented/architecture/2026-06-24-web-capability-seam.md),在同一个 `ctx.web` 服务上横跨**两项能力**(search 与 fetch),并拆分到多个包:接口([dsh-web](../../packages/web/web),`ctx.web` + 提供方注册表)、实现([dsh-web-search-exa](../../packages/web/web-search-exa)、[dsh-web-search-perplexity](../../packages/web/web-search-perplexity)、[dsh-web-search-deepseek](../../packages/web/web-search-deepseek)、[dsh-web-fetch-local](../../packages/web/web-fetch-local))与消费方([dsh-tool-web](../../packages/web/tool-web),即 `web_search`/`web_fetch` 工具 schema)。Web 是**一项可选能力**,不属于 agent loop 主干,因此其词汇定义在此而非 [core.md](core.md) 中。更换 search 提供方不会改变模型请求 query 的方式,更换 fetch 实现也不会改变模型请求 URL 的方式。
源码:[`packages/web/web/src/types.ts`](../../packages/web/web/src/types.ts)
@@ -15,20 +15,37 @@ Web 访问 seam 是一个[能力 seam](../rfc/implemented/architecture/2026-06-2
面向模型的工具参数仅为一个 `query`;`maxResults` 是消费方自有的上限(`dsh-tool-web` 的 `searchMaxResults` 配置,默认 `8`),通过 seam 传递并在返回时强制执行——如果提供方返回超量,seam 截断 `sources[]` 并设置 `truncated`。
```ts type-equiv
+/**
+ * What one search-capable backend can return. The model-facing argument is just
+ * a query; `maxResults` is a `dsh-tool-web`-layer bound passed through unchanged
+ * and enforced on the way back by the seam (see {@link WebSearchResult}).
+ */
interface WebSearchRequest {
readonly query: string
/**
* Upper bound on returned sources; the seam truncates to it. Omitted = no
- * bound. `dsh-tool-web` always sets it.
+ * bound. `dsh-tool-web` always sets it. A provider whose API supports a
+ * result-count control (Exa's `numResults`) should apply it at the request
+ * layer as a cost/latency optimization; the seam enforces the bound
+ * regardless.
*/
readonly maxResults?: number
}
```
```ts type-equiv
+/**
+ * Normalized search outcome. `content` is optional provider-generated answer
+ * text or summary (Exa returns none; Perplexity returns a generated answer).
+ * `sources[]` is the portable citation surface. `truncated` is set by the seam
+ * when it cut `sources[]` down to `maxResults`.
+ */
interface WebSearchResult {
+ /** Optional provider-generated answer text, search context, or summary. */
readonly content?: string
+ /** Citeable sources, already truncated to the request's `maxResults`. */
readonly sources: readonly WebSearchSource[]
+ /** True when the seam dropped sources to honor `maxResults`. */
readonly truncated: boolean
}
```
@@ -36,10 +53,17 @@ interface WebSearchResult {
`content` 是提供方可选生成的回答文本(Exa 和 DeepSeek 不返回;Perplexity 返回生成式回答)。`sources[]` 是可移植的引用表面。一个 source 必有 `url`;`title`/`snippet`/`publishedAt` 可选,因为并非每个提供方都返回它们——Perplexity 的引用可能只有 URL,强迫适配器编造其余字段会让 seam 说谎。`dsh-tool-web` 渲染时使用 `title ?? hostname(url)`。
```ts type-equiv
+/**
+ * One citeable source. A source always has a URL; `title`, `snippet`, and
+ * `publishedAt` are optional because not every provider returns them — forcing
+ * adapters to invent them would make the seam lie (Perplexity citations may be
+ * URL-only). `dsh-tool-web` renders `title ?? hostname(url)` for display.
+ */
interface WebSearchSource {
readonly url: string
readonly title?: string
readonly snippet?: string
+ /** Publication/crawl timestamp as a provider-supplied ISO-8601 string. */
readonly publishedAt?: string
}
```
@@ -47,6 +71,12 @@ interface WebSearchSource {
## 抓取请求与结果
```ts type-equiv
+/**
+ * What one fetch-capable backend is asked to retrieve. The request deliberately
+ * omits timeout, format, prompt, and extraction controls: cancellation is a
+ * direct execution argument, while presentation and higher-level LLM concerns
+ * belong outside safe retrieval.
+ */
interface WebFetchRequest {
readonly url: string
}
@@ -55,10 +85,20 @@ interface WebFetchRequest {
HTTP 状态码是被抓取资源状态的一部分,不自动视为失败:成功的网络抓取返回 `404`/`500` 时,仍产出一个带状态码和有界解码 body 的 `WebFetchResult`。`url` 是经过允许的重定向后的最终 URL。`WebError` 仅用于无法安全获取或表示资源的情况。
```ts type-equiv
+/**
+ * Normalized fetch outcome. A successful network fetch of a non-2xx response is
+ * a result, not an error: the status code is part of the fetched resource
+ * state. {@link WebError} is reserved for failures to safely retrieve or
+ * represent the resource.
+ */
interface WebFetchResult {
+ /** The final URL after allowed redirects (the request URL is in the request). */
readonly url: string
+ /** HTTP status code of the fetched response. */
readonly statusCode: number
+ /** Decoded body, classified by content kind. */
readonly body: WebFetchBody
+ /** True when the provider capped the decoded body. */
readonly truncated: boolean
}
```
@@ -66,6 +106,15 @@ interface WebFetchResult {
`WebFetchBody` 是 `dsh-web` 拥有的**封闭**可辨识联合类型(不是可合并扩展的 map):提供方解码 kind,`dsh-tool-web` 渲染它,因此新增一个 kind 是已知包之间的协调变更,而非插件扩展。消费方对 `kind` 做 `switch` 并以 `default: assertNever(...)` 结尾,所以新增 kind 会在每个消费方处编译失败,直到被处理。即使各分支当前字段一致,每个分支仍保持独立的对象字面量,为将来分支特有字段留出空间(例如未来 `pdf` body 的 `pageCount`)。
```ts type-equiv
+/**
+ * The decoded body of a fetched resource. A CLOSED discriminated union owned by
+ * `dsh-web`: the provider decodes the kind and `dsh-tool-web` renders it, so a
+ * new kind is a coordinated change across known packages, not a plugin
+ * extension. Consumers `switch` on `kind` ending in `default: assertNever(...)`
+ * so adding a kind breaks compilation at every consumer until handled. Each arm
+ * stays its own object literal even where fields coincide today, leaving room
+ * for arm-specific fields later (a `pdf` body's `pageCount`).
+ */
type WebFetchBody =
| { readonly kind: 'html'; readonly content: string }
| { readonly kind: 'text'; readonly content: string }
diff --git a/docs/core-data-structures/workflow.i18n.yaml b/docs/core-data-structures/workflow.i18n.yaml
index 19a2d0db9e..cb0bf7e961 100644
--- a/docs/core-data-structures/workflow.i18n.yaml
+++ b/docs/core-data-structures/workflow.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-workflow.md: 1571723c172fe851e89550e4ed8588ddb14088a0
-workflow.zh.md: 553d8fa8122b3c9f0cd29840cb2a72d9d5ae6e83
+workflow.md: 8d271b89e71de6f6bef548aa8da61402ef9ada6e
+workflow.zh.md: 335f08cefe057bdc0d0f78a90e8301d5e457aae7
diff --git a/docs/core-data-structures/workflow.zh.md b/docs/core-data-structures/workflow.zh.md
index 553d8fa812..335f08cefe 100644
--- a/docs/core-data-structures/workflow.zh.md
+++ b/docs/core-data-structures/workflow.zh.md
@@ -4,20 +4,44 @@
工作流 seam:一个 agent(智能体)运行由模型编写的编排脚本(SCRIPT),扇出 subagent。与 [subagent](subagent.md) 一样,它是**一项可选能力**,不属于 agent loop(智能体循环)主干,因此其词汇定义在此处而非 [core.md](core.md)。与 subagent 注册表不同,它采用 bash 形态:每个上下文只有一个引擎实现提供 `ctx.workflows`;没有命名提供方注册表(第二个引擎是插件替换,而非共存)。
-接口:[dsh-workflow](../../packages/workflow/workflow)(`ctx.workflows` + 下文词汇)。实现是 [dsh-workflow-workerthread](../../packages/workflow/workflow-workerthread)(一个 `node:worker_threads` 引擎:每次运行一个 worker,脚本的 vm 上下文在其中执行);面向模型的消费方是 [dsh-tool-workflow](../../packages/workflow/tool-workflow)。提案与设计动机见[动态工作流 RFC](../rfc/implemented/feature/2026-07-05-dynamic-workflows.md)。
+接口:[dsh-workflow](../../packages/workflow/workflow)(`ctx.workflows` + 下文词汇)。实现是 [dsh-workflow-workerthread](../../packages/workflow/workflow-workerthread)(一个 `node:worker_threads` 引擎——每个 run 一个 worker,脚本的 vm context 位于其中);面向模型的消费方是 [dsh-tool-workflow](../../packages/workflow/tool-workflow)。提案与设计理由见 [dynamic-workflows Agent Note(agent 决策记录)](../../.agents/notes/implemented/feature/2026-07-05-dynamic-workflows.md)。
源码:[`packages/workflow/workflow/src/types.ts`](../../packages/workflow/workflow/src/types.ts)
## 启动请求
-调用方启动一次运行时提交的内容。工具层从模型的 `{ script, meta, args }` 调用加上发起调用的 agent 构建此请求;`meta` 和 `args` 是纯 JSON 数据(引擎在任何代码执行之前对 `meta` 做形状校验,不通过则立即报错:永远不会为了获取 meta 而执行脚本文本)。`parent` 是必填项:脚本 spawn 的每个子 agent 都归属于它(cwd、血统与深度通过 [subagent seam](subagent.md) 传递)。
+调用方启动 run 时提出的请求。普通 workflow 工具根据模型的 `{ script, meta, args }` 调用与发起调用的 agent 构建它;专用消费方还可以为该 run 选择一个引擎级 `subagentProvider` 并调低 `maxTotalAgents`,但脚本无法观察或替换这两项策略。`meta` 与 `args` 是普通 JSON 数据(引擎会对 `meta` 做形状校验,并在任何内容运行前大声拒绝——绝不会通过求值脚本文本来获取它)。`parent` 是必填字段——脚本生成的每个子 agent 都归属于它(cwd、谱系与深度通过 [subagent seam](subagent.md) 流转)。
```ts type-equiv
+/**
+ * What a caller asks for when starting a workflow run. `meta` and `args` are
+ * plain JSON DATA by the seam contract (the tool builds both from the model's
+ * schema-validated call; the engine validates `meta`'s shape and rejects loud
+ * before anything runs) — an engine never evaluates script text to obtain
+ * them. `parent` is REQUIRED — every `agent()` the script spawns is
+ * attributed to it (cwd, lineage, depth flow through the subagent seam).
+ */
interface WorkflowStartRequest {
+ /** The plain-JS script body (top-level await allowed; ends with `return `). */
script: string
+ /** The workflow's identity block, as plain JSON data (shape-validated by the engine). */
meta: WorkflowMeta
+ /** Optional input exposed verbatim to the script as the `args` global. */
args?: unknown
+ /**
+ * Optional engine-wide child-provider override for this run. The workflow
+ * script cannot observe or replace it; omission uses the engine's configured
+ * provider.
+ */
+ subagentProvider?: string
+ /**
+ * Optional per-run total-child ceiling. Implementations reject values above
+ * their deployment ceiling before publishing the run.
+ */
+ maxTotalAgents?: number
+ /** The agent on whose behalf the run executes (parent of every child). */
parent: Agent
+ /** Cancels the run when aborted (the tool's `exec.signal`). */
signal?: AbortSignal
}
```
@@ -27,10 +51,21 @@ interface WorkflowStartRequest {
作为数据附在启动请求上的身份块(工具的 `meta` 参数;字段词汇与 Claude Code 动态工作流的 meta 块一致)。`phases` 仅用于进度展示:`phase()` 调用与标题匹配,供观察者使用;不暗示任何执行结构。
```ts type-equiv
+/**
+ * The script's identity block, provided as plain JSON data alongside the
+ * script body (the model-facing tool carries it as its `meta` parameter) and
+ * validated by the engine before the body runs. `name`/`description` are
+ * required; the rest is optional annotation. The field vocabulary matches the
+ * Claude Code dynamic-workflows meta block.
+ */
interface WorkflowMeta {
+ /** Short kebab-case workflow name (display + persistence key). */
name: string
+ /** One-line description of what the workflow does. */
description: string
+ /** Optional guidance on when this workflow applies (shown in listings). */
whenToUse?: string
+ /** Optional phase declarations matched by `phase()` calls. */
phases?: WorkflowPhase[]
}
```
@@ -40,10 +75,27 @@ interface WorkflowMeta {
一次运行的结果,由 `WorkflowRun.result` resolve。`value` 是脚本的物化返回值——纯宿主域 JSON 数据(脚本无返回值时为 `null`)——仅在 `completed` 时有意义。`stopReason` 是封闭联合类型(引擎所有;消费方可穷举):`completed` | `cancelled` | `error`。非 `completed` 的原因在 `error` 中携带失败信息,消费方将其映射为 `isError` 工具结果,而非把部分输出当作成功上报。
```ts type-equiv
+/**
+ * The outcome of one run, resolved by {@link WorkflowRun.result}. `value` is
+ * the script's materialized return value (plain host-realm JSON data; `null`
+ * when the script returned `undefined`) — meaningful only for `completed`.
+ * A non-`completed` reason carries the failure in `error`; the consumer maps
+ * it to an `isError` tool result rather than reporting partial output.
+ */
interface WorkflowResult {
+ /** The script's return value (host JSON data; `null` for no return). */
value: unknown
+ /** Why the run settled. */
stopReason: WorkflowStopReason
+ /** The failure message (present iff `stopReason` is not `completed`). */
error?: string
+ /**
+ * How many `agent()` calls the run accepted over its whole lifetime. On a
+ * graceful settlement this is the script-side count (calls still queued for
+ * a concurrency slot included); on a termination path (grace force-settle,
+ * worker death) it degrades to the host-observed count — calls queued
+ * inside a terminated script are unknowable then.
+ */
agentsStarted: number
}
```
@@ -53,11 +105,20 @@ interface WorkflowResult {
脚本执行期间消费方持有的句柄。消费方 await `result`,可中途 `cancel`,且必须在每条路径上 `dispose`。`result` 不会 reject:脚本失败以 `stopReason: 'error'` resolve;一旦运行被取消,即使脚本本身永不 settle,它也会在引擎的有界宽限期内 settle(引擎强制以 `cancelled` settle;worker-thread 引擎随后终止脚本的 worker),因此消费方 await `result` 不会在取消后卡死。`dispose()` = cancel + 有界 settle + 等待子 agent 停稳;它不会因脚本卡死而挂起。
```ts type-equiv
+/**
+ * Holder-owned live workflow. `result` never rejects and settles within the
+ * engine's cancellation grace; failures resolve through `stopReason`. Consumers
+ * may cancel and must call idempotent `dispose()` on every path to await bounded
+ * script settlement and child quiescence.
+ */
interface WorkflowRun {
readonly id: WorkflowRunId
+ /** The validated meta block (available before the body runs). */
readonly meta: WorkflowMeta
readonly result: Promise
+ /** Cancel the run: children abort, pending hooks reject, the script dies at its next await (or is force-settled at the grace). */
cancel(reason?: string): void
+ /** Cancel + bounded-grace settle; safe to call on every path (idempotent). */
dispose(): Promise
}
```
diff --git a/docs/postmortem/0001-acp-default-export-drops-inject.i18n.yaml b/docs/postmortem/0001-acp-default-export-drops-inject.i18n.yaml
index 2affb91142..bc2b7d097a 100644
--- a/docs/postmortem/0001-acp-default-export-drops-inject.i18n.yaml
+++ b/docs/postmortem/0001-acp-default-export-drops-inject.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-0001-acp-default-export-drops-inject.md: 6a71d8d7ef72e3110a99774b180f3de7115ef622
-0001-acp-default-export-drops-inject.zh.md: d12feca2eb1a35b68e191945562aabe25e043e37
+0001-acp-default-export-drops-inject.md: ab3efc880cb5290dc149b6bacb276ccf581968c1
+0001-acp-default-export-drops-inject.zh.md: caf60dc086e892af4ae3563b0bf073c7e6373602
diff --git a/docs/postmortem/0001-acp-default-export-drops-inject.zh.md b/docs/postmortem/0001-acp-default-export-drops-inject.zh.md
index d12feca2eb..caf60dc086 100644
--- a/docs/postmortem/0001-acp-default-export-drops-inject.zh.md
+++ b/docs/postmortem/0001-acp-default-export-drops-inject.zh.md
@@ -26,7 +26,7 @@ ACP 服务器无法创建或加载任何一个会话——而这正是编辑器
## 根因 #1——`export default apply` 丢弃了插件的 `inject`(导致 `session/new` 崩溃)
-`packages/ui/acp/src/index.ts` 是一个*命名空间插件*:它将 `name`、`inject`、`Config` 和 `apply` 作为独立的命名导出——与仓库中其他所有插件(`invariants`、`llm-deepseek`、`tool-bash`、`stdio-chat` 等)形状相同。但它*还*多了一行其他插件都没有的代码:
+`packages/ui/acp/src/index.ts` 是一个*命名空间插件*:它将 `name`、`inject`、`Config` 和 `apply` 作为独立的命名导出——与仓库中其他所有插件(`invariants`、`llm-deepseek`、`tool-bash`、`tui` 等)形状相同。但它*还*多了一行其他插件都没有的代码:
```ts ignore-check
export const name = 'acp'
diff --git a/docs/postmortem/0002-js-expression-disabled-filesystem-tools.i18n.yaml b/docs/postmortem/0002-js-expression-disabled-filesystem-tools.i18n.yaml
index 34b22884f8..21f7000078 100644
--- a/docs/postmortem/0002-js-expression-disabled-filesystem-tools.i18n.yaml
+++ b/docs/postmortem/0002-js-expression-disabled-filesystem-tools.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-0002-js-expression-disabled-filesystem-tools.md: 43e57a6bd1b68f38c47eeda3c3abb8455024b350
-0002-js-expression-disabled-filesystem-tools.zh.md: ce091a4f6bd19dd9ccb9100583e92589998a1906
+0002-js-expression-disabled-filesystem-tools.md: 30ff9d920821a8d55c4bea5f120f1aeeca6634b3
+0002-js-expression-disabled-filesystem-tools.zh.md: d171ce7fe0fea830375f7494be2aac38630c8d6a
diff --git a/docs/postmortem/0002-js-expression-disabled-filesystem-tools.zh.md b/docs/postmortem/0002-js-expression-disabled-filesystem-tools.zh.md
index ce091a4f6b..d171ce7fe0 100644
--- a/docs/postmortem/0002-js-expression-disabled-filesystem-tools.zh.md
+++ b/docs/postmortem/0002-js-expression-disabled-filesystem-tools.zh.md
@@ -6,7 +6,7 @@ Status: resolved
## 概要
-ACP(Agent Client Protocol)示例试图通过 `disabled: !!js ...` 有条件地启用文件系统插件,但 Cordis 仅在插件 `config` 内部对 JavaScript 表达式求值。原始的表达式对象为 truthy,因此文件系统栈始终处于禁用状态。快照刷新随后将 `UNKNOWN_TOOL` 结果接受为新的 golden 基准。修复方案改用显式的文件系统 overlay,并增加了静态配置守卫和快照结果守卫。
+ACP(Agent Client Protocol)示例试图通过 `disabled: !!js ...` 有条件地启用文件系统插件,但 Cordis 仅在插件 `config` 内部对 JavaScript 表达式求值。原始的表达式对象为 truthy,因此文件系统栈始终处于禁用状态。快照刷新随后将 `UNKNOWN_TOOL` 结果接受为新的预期输出。修复方案改用显式的文件系统 overlay,并增加了静态配置守卫和快照结果守卫。
## 摘要
@@ -24,7 +24,7 @@ Cordis Include 将每个 `!!js` 标量解析为一个表达式对象。Loader
- PR #261 整合了 ACP 组合并刷新了文件系统快照,同时引入了条件式文件系统入口。
- 所有单元测试、覆盖率、快照、文档、构建和 hygiene 检查均通过。
-- 对刷新后的文件系统 golden 的评审发现了通用的失败卡片和结构化的 `UNKNOWN_TOOL` 结果。
+- 对刷新后的文件系统预期输出的评审发现了通用的失败卡片和结构化的 `UNKNOWN_TOOL` 结果。
- 一次真实的 Loader 启动确认:每个 `disabled` 值仍为表达式对象,每个文件系统 fiber 均未创建。
## 根因
@@ -38,10 +38,10 @@ Cordis Include 将每个 `!!js` 标量解析为一个表达式对象。Loader
- 文件系统场景启动 `fs.cordis.yml`:一个显式的固定全权限 overlay,配有对应的 replay 配置和独立的 request-header 类。
- [`AGENTS.md`](../../AGENTS.md) 与 [Cordis 入门](../cordis-primer.md#loader-configuration)明确说明 `!!js` 仅在插件 `config` 内有效,条件式组合应使用 overlay。
- `verify-cordis-config` 解析仓库中的 Cordis YAML,拒绝 Loader 入口元数据中的表达式节点(包括 include patch 和插入的入口)。
-- `dsh-acp-snapshot` 在新鲜运行和已提交的会话 fixture 中拒绝结构化的 `UNKNOWN_TOOL` 结果,防止其成为被接受的 golden 基准。
+- `dsh-acp-snapshot` 在新鲜运行和已提交的会话 fixture 中拒绝结构化的 `UNKNOWN_TOOL` 结果,防止其被提交为预期输出。
## 教训
- 语法上被接受的配置值不一定在该位置被求值;应记录并验证插值边界。
-- 快照刷新是 fixture 的生产过程,不是正确性审查。诸如已注册工具缺失这类语义上不可能的结果,需要独立于 golden 的断言。
+- 快照刷新是 fixture 的生产过程,不是正确性审查。诸如已注册工具缺失这类语义上不可能的结果,需要独立于预期输出的断言。
- 权限控制只应描述其实际管辖的能力。组合时的文件系统访问无法安全地跟随运行时的 bash-only 预设。
diff --git a/docs/postmortem/README.i18n.yaml b/docs/postmortem/README.i18n.yaml
index 1fb6e7d64f..6673537b87 100644
--- a/docs/postmortem/README.i18n.yaml
+++ b/docs/postmortem/README.i18n.yaml
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
-README.md: 4dc59e4f5e70f51c4c0baa64fbe34b213f2a7c3d
-README.zh.md: b959566d6e2659957d9b6b121303cc4d0e7c4c4e
+README.md: df0e2fcb8540aeed005153dbecc451d781ca5ff1
+README.zh.md: 1b099919720867dbc8b6766121bff22d3f221c4c
diff --git a/docs/postmortem/README.zh.md b/docs/postmortem/README.zh.md
index b959566d6e..1b09991972 100644
--- a/docs/postmortem/README.zh.md
+++ b/docs/postmortem/README.zh.md
@@ -4,7 +4,7 @@
事故复盘:一个 bug 到达了它不该到达的地方(真实用户、已合并的 PR(Pull Request)、已发布的版本),值得关注的是*为什么我们的流程放过了它*,而不仅仅是那一行修复。
-事故复盘不是 [RFC](../rfc/README.md)(RFC 记录一个经过深思熟虑的设计决策及其被否决的替代方案,或提出未来工作)。它是一份回顾性的失败记录:什么坏了、机制是什么、为什么每道安全网都没拦住、以及加了哪些具体的防护措施使同类 bug 下次能被显式暴露。
+事故复盘不是 [Agent Note(agent 决策记录)](../../.agents/notes/README.md)(Agent Note 记录一个经过深思熟虑的设计决策及其被否决的替代方案,或提出未来工作)。它是一份回顾性的失败记录:什么坏了、机制是什么、为什么每道安全网都没拦住、以及加了哪些具体的防护措施使同类 bug 下次能被显式暴露。
当一个 bug 满足以下条件时,请撰写事故复盘:**隐蔽**(机制不显而易见,即使是细心的工程师也得费力重新推导)、**系统性**(逃逸的原因是测试/工具/约定的缺口,而非一次性的笔误)、**重新发现的代价高**(它消耗了真实的调试时间,且下次还会如此)。请链接该事故复盘所推动建立的防护措施(测试、AGENTS.md 规则、ADR)。
diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json
index 2ac67aa892..12b3359f1e 100644
--- a/scripts/type-equiv.manifest.json
+++ b/scripts/type-equiv.manifest.json
@@ -131,7 +131,11 @@
"symbol": "Scope",
"source": "packages/core/scope/src/index.ts"
},
- { "doc": "docs/core-data-structures/scope.md", "symbol": "ScopeLayer", "source": "packages/core/scope/src/store.ts" },
+ {
+ "doc": "docs/core-data-structures/scope.md",
+ "symbol": "ScopeLayer",
+ "source": "packages/core/scope/src/store.ts"
+ },
{
"doc": "docs/core-data-structures/goal.md",
"symbol": "GoalRef",
@@ -284,7 +288,11 @@
"symbol": "SessionEventMap",
"source": "packages/core/session/src/types.ts"
},
- { "doc": "docs/core-data-structures/session.md", "symbol": "OutOfBandSessionEventMap", "source": "packages/core/session/src/types.ts" },
+ {
+ "doc": "docs/core-data-structures/session.md",
+ "symbol": "OutOfBandSessionEventMap",
+ "source": "packages/core/session/src/types.ts"
+ },
{
"doc": "docs/core-data-structures/session.md",
"symbol": "EpochHeader",
@@ -411,18 +419,61 @@
"symbol": "SessionEventTrace",
"source": "packages/session-query/session-query/src/types.ts"
},
-
- { "doc": "docs/core-data-structures/session-title.md", "symbol": "SessionTitleProviderId", "source": "packages/session-title/session-title/src/index.ts" },
- { "doc": "docs/core-data-structures/session-title.md", "symbol": "SessionTitleModelProvenance", "source": "packages/session-title/session-title/src/index.ts" },
- { "doc": "docs/core-data-structures/session-title.md", "symbol": "SessionTitleSource", "source": "packages/session-title/session-title/src/index.ts" },
- { "doc": "docs/core-data-structures/session-title.md", "symbol": "SessionTitleEventData", "source": "packages/session-title/session-title/src/index.ts" },
- { "doc": "docs/core-data-structures/session-title.md", "symbol": "SessionTitleSnapshot", "source": "packages/session-title/session-title/src/index.ts" },
- { "doc": "docs/core-data-structures/session-title.md", "symbol": "SessionTitleLlmRequestEventData", "source": "packages/session-title/session-title-llm/src/index.ts" },
- { "doc": "docs/core-data-structures/session-title.md", "symbol": "SessionTitleUserMessage", "source": "packages/session-title/session-title/src/index.ts" },
- { "doc": "docs/core-data-structures/session-title.md", "symbol": "SessionTitleAutomaticMode", "source": "packages/session-title/session-title/src/index.ts" },
- { "doc": "docs/core-data-structures/session-title.md", "symbol": "SessionTitleProviderRequest", "source": "packages/session-title/session-title/src/index.ts" },
- { "doc": "docs/core-data-structures/session-title.md", "symbol": "SessionTitleProviderResult", "source": "packages/session-title/session-title/src/index.ts" },
- { "doc": "docs/core-data-structures/session-title.md", "symbol": "SessionTitleProvider", "source": "packages/session-title/session-title/src/index.ts" },
+ {
+ "doc": "docs/core-data-structures/session-title.md",
+ "symbol": "SessionTitleProviderId",
+ "source": "packages/session-title/session-title/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session-title.md",
+ "symbol": "SessionTitleModelProvenance",
+ "source": "packages/session-title/session-title/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session-title.md",
+ "symbol": "SessionTitleSource",
+ "source": "packages/session-title/session-title/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session-title.md",
+ "symbol": "SessionTitleEventData",
+ "source": "packages/session-title/session-title/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session-title.md",
+ "symbol": "SessionTitleSnapshot",
+ "source": "packages/session-title/session-title/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session-title.md",
+ "symbol": "SessionTitleLlmRequestEventData",
+ "source": "packages/session-title/session-title-llm/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session-title.md",
+ "symbol": "SessionTitleUserMessage",
+ "source": "packages/session-title/session-title/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session-title.md",
+ "symbol": "SessionTitleAutomaticMode",
+ "source": "packages/session-title/session-title/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session-title.md",
+ "symbol": "SessionTitleProviderRequest",
+ "source": "packages/session-title/session-title/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session-title.md",
+ "symbol": "SessionTitleProviderResult",
+ "source": "packages/session-title/session-title/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session-title.md",
+ "symbol": "SessionTitleProvider",
+ "source": "packages/session-title/session-title/src/index.ts"
+ },
{
"doc": "docs/core-data-structures/tools.md",
"symbol": "ToolDefinition",
@@ -992,6 +1043,794 @@
"doc": "docs/core-data-structures/lsp.md",
"symbol": "LspService",
"source": "packages/lsp/lsp/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "Branded",
+ "source": "packages/util/brand/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "ContentBlockMap",
+ "source": "packages/llm/llm/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "AssistantProvenance",
+ "source": "packages/llm/llm/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "Message",
+ "source": "packages/llm/llm/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "MessageSourceMap",
+ "source": "packages/llm/llm/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "FinishReasonMap",
+ "source": "packages/llm/llm/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "LlmProviderInfo",
+ "source": "packages/llm/llm/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "LlmModelInfo",
+ "source": "packages/llm/llm/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "LlmModelContext",
+ "source": "packages/llm/llm/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "GenerateOptions",
+ "source": "packages/llm/llm/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "ToolSchema",
+ "source": "packages/llm/llm/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "LlmCallConfig",
+ "source": "packages/llm/llm/src/call-config.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "SessionEvent",
+ "source": "packages/core/session/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "AgentCancelCause",
+ "source": "packages/core/agent/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "InjectOptions",
+ "source": "packages/core/agent/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "Agent",
+ "source": "packages/core/agent/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "HookContext",
+ "source": "packages/core/agent/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "PromptDecision",
+ "source": "packages/core/agent/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "ContinuationDecision",
+ "source": "packages/core/agent/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "RequestError",
+ "source": "packages/core/agent/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "RequestErrorDecision",
+ "source": "packages/core/agent/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "ContinuationStop",
+ "source": "packages/core/agent/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/core.zh.md",
+ "symbol": "SessionStartSource",
+ "source": "packages/core/agent/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/scope.zh.md",
+ "symbol": "ScopeKey",
+ "source": "packages/core/scope/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/scope.zh.md",
+ "symbol": "Scoped",
+ "source": "packages/core/scope/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/scope.zh.md",
+ "symbol": "Scope",
+ "source": "packages/core/scope/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/scope.zh.md",
+ "symbol": "ScopeLayer",
+ "source": "packages/core/scope/src/store.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/system-prompt.zh.md",
+ "symbol": "AssembleContext",
+ "source": "packages/core/system-prompt/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/system-prompt.zh.md",
+ "symbol": "PromptSection",
+ "source": "packages/core/system-prompt/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/system-prompt.zh.md",
+ "symbol": "ToolProviderResult",
+ "source": "packages/core/system-prompt/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/llm-streaming.zh.md",
+ "symbol": "StreamChunk",
+ "source": "packages/llm/llm/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/llm-streaming.zh.md",
+ "symbol": "LlmFailure",
+ "source": "packages/llm/llm/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/llm-streaming.zh.md",
+ "symbol": "TokenUsage",
+ "source": "packages/llm/llm/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/llm-streaming.zh.md",
+ "symbol": "ContentBlockMap",
+ "source": "packages/llm/llm/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/llm-streaming.zh.md",
+ "symbol": "AppIdentity",
+ "source": "packages/llm/llm/src/attribution.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/llm-streaming.zh.md",
+ "symbol": "BlockAssembler",
+ "source": "packages/llm/llm/src/assembler.ts",
+ "projection": "public-api"
+ },
+ {
+ "doc": "docs/core-data-structures/llm-streaming.zh.md",
+ "symbol": "LlmAdapter",
+ "source": "packages/llm/llm/src/index.ts",
+ "projection": "public-api"
+ },
+ {
+ "doc": "docs/core-data-structures/session.zh.md",
+ "symbol": "SessionEventMap",
+ "source": "packages/core/session/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session.zh.md",
+ "symbol": "OutOfBandSessionEventMap",
+ "source": "packages/core/session/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session.zh.md",
+ "symbol": "EpochHeader",
+ "source": "packages/core/session/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session.zh.md",
+ "symbol": "TodoItem",
+ "source": "packages/core/session/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session.zh.md",
+ "symbol": "SessionEvent",
+ "source": "packages/core/session/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session.zh.md",
+ "symbol": "TurnTriggerMap",
+ "source": "packages/core/session/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session.zh.md",
+ "symbol": "TurnEndReasonMap",
+ "source": "packages/core/session/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session.zh.md",
+ "symbol": "SurfaceEventType",
+ "source": "packages/core/session/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session.zh.md",
+ "symbol": "SurfaceOp",
+ "source": "packages/core/session/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session.zh.md",
+ "symbol": "SurfaceIntent",
+ "source": "packages/core/session/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session.zh.md",
+ "symbol": "SessionSurface",
+ "source": "packages/core/session/src/surface.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session.zh.md",
+ "symbol": "SurfaceFoldReplacement",
+ "source": "packages/core/session/src/surface.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session.zh.md",
+ "symbol": "SurfaceFoldResult",
+ "source": "packages/core/session/src/surface.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session.zh.md",
+ "symbol": "Session",
+ "source": "packages/core/session/src/index.ts",
+ "projection": "public-api"
+ },
+ {
+ "doc": "docs/core-data-structures/persistence.zh.md",
+ "symbol": "SessionHeader",
+ "source": "packages/core/session/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/persistence.zh.md",
+ "symbol": "CreateSessionOptions",
+ "source": "packages/core/session/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/persistence.zh.md",
+ "symbol": "SessionLocation",
+ "source": "packages/session-persistence/session-persistence/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session-query.zh.md",
+ "symbol": "SessionEventSurface",
+ "source": "packages/session-query/session-query/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session-query.zh.md",
+ "symbol": "SessionRecord",
+ "source": "packages/session-query/session-query/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session-query.zh.md",
+ "symbol": "SessionEventRecord",
+ "source": "packages/session-query/session-query/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session-query.zh.md",
+ "symbol": "SessionLineageNode",
+ "source": "packages/session-query/session-query/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session-query.zh.md",
+ "symbol": "SessionLineageTrace",
+ "source": "packages/session-query/session-query/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session-query.zh.md",
+ "symbol": "SessionQueryErrorCode",
+ "source": "packages/session-query/session-query/src/config.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session-query.zh.md",
+ "symbol": "SessionEventReadRequest",
+ "source": "packages/session-query/session-query/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session-query.zh.md",
+ "symbol": "SessionEventWindow",
+ "source": "packages/session-query/session-query/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session-query.zh.md",
+ "symbol": "SessionEventTraceRequest",
+ "source": "packages/session-query/session-query/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/session-query.zh.md",
+ "symbol": "SessionEventTrace",
+ "source": "packages/session-query/session-query/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/tools.zh.md",
+ "symbol": "ToolDefinition",
+ "source": "packages/core/tools/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/tools.zh.md",
+ "symbol": "SchemaProp",
+ "source": "packages/core/tools/src/schema.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/tools.zh.md",
+ "symbol": "SchemaSpec",
+ "source": "packages/core/tools/src/schema.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/tools.zh.md",
+ "symbol": "InferArgs",
+ "source": "packages/core/tools/src/schema.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/tools.zh.md",
+ "symbol": "ToolExecutionToken",
+ "source": "packages/core/tools/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/tools.zh.md",
+ "symbol": "ToolExecutionInput",
+ "source": "packages/core/tools/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/tools.zh.md",
+ "symbol": "ToolExecution",
+ "source": "packages/core/tools/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/tools.zh.md",
+ "symbol": "ToolDispatchExecution",
+ "source": "packages/core/tools/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/tools.zh.md",
+ "symbol": "ToolExecutionMode",
+ "source": "packages/core/tools/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/tools.zh.md",
+ "symbol": "ToolRunContext",
+ "source": "packages/core/tools/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/tools.zh.md",
+ "symbol": "ToolGuard",
+ "source": "packages/core/tools/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/tools.zh.md",
+ "symbol": "ToolRestriction",
+ "source": "packages/core/tools/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/tools.zh.md",
+ "symbol": "ToolExecutionResult",
+ "source": "packages/core/tools/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/tools.zh.md",
+ "symbol": "PreToolDecision",
+ "source": "packages/core/tools/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/tools.zh.md",
+ "symbol": "PostToolDecision",
+ "source": "packages/core/tools/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/tools.zh.md",
+ "symbol": "StructuredScalar",
+ "source": "packages/core/tools/src/json-schema.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/tools.zh.md",
+ "symbol": "StructuredSchemaType",
+ "source": "packages/core/tools/src/json-schema.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/tools.zh.md",
+ "symbol": "StructuredSchemaNode",
+ "source": "packages/core/tools/src/json-schema.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/tools.zh.md",
+ "symbol": "StructuredOutputSchema",
+ "source": "packages/core/tools/src/json-schema.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/user-interaction.zh.md",
+ "symbol": "AskUserQuestionOption",
+ "source": "packages/ui/user-interaction/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/user-interaction.zh.md",
+ "symbol": "AskUserQuestionItem",
+ "source": "packages/ui/user-interaction/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/user-interaction.zh.md",
+ "symbol": "AskUserQuestionRequest",
+ "source": "packages/ui/user-interaction/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/user-interaction.zh.md",
+ "symbol": "AskUserQuestionAnswerItem",
+ "source": "packages/ui/user-interaction/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/user-interaction.zh.md",
+ "symbol": "AskUserQuestionAnswer",
+ "source": "packages/ui/user-interaction/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/user-interaction.zh.md",
+ "symbol": "UserInteractionProvider",
+ "source": "packages/ui/user-interaction/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/user-interaction.zh.md",
+ "symbol": "UserInteractionError",
+ "source": "packages/ui/user-interaction/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/approval.zh.md",
+ "symbol": "ApprovalRequestId",
+ "source": "packages/ui/user-approval/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/approval.zh.md",
+ "symbol": "ApprovalOutcome",
+ "source": "packages/ui/user-approval/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/approval.zh.md",
+ "symbol": "ApprovalPolicy",
+ "source": "packages/ui/user-approval/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/approval.zh.md",
+ "symbol": "ApprovalRequest",
+ "source": "packages/ui/user-approval/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/bash.zh.md",
+ "symbol": "DshEnvironmentKey",
+ "source": "packages/bash/bash/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/bash.zh.md",
+ "symbol": "DshEnvironment",
+ "source": "packages/bash/bash/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/bash.zh.md",
+ "symbol": "BashExecRequest",
+ "source": "packages/bash/bash/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/bash.zh.md",
+ "symbol": "BashExecSpec",
+ "source": "packages/bash/bash/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/bash.zh.md",
+ "symbol": "BashRunResult",
+ "source": "packages/bash/bash/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/bash.zh.md",
+ "symbol": "BashSandboxInfo",
+ "source": "packages/bash/bash/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/bash.zh.md",
+ "symbol": "CollectedOutput",
+ "source": "packages/bash/bash/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/bash.zh.md",
+ "symbol": "BashProcess",
+ "source": "packages/bash/bash/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/bash.zh.md",
+ "symbol": "BashProcessRead",
+ "source": "packages/bash/bash/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/sandbox.zh.md",
+ "symbol": "SandboxMode",
+ "source": "packages/sandbox/sandbox/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/sandbox.zh.md",
+ "symbol": "ConfinedSandboxMode",
+ "source": "packages/sandbox/sandbox/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/sandbox.zh.md",
+ "symbol": "SandboxExecutionPolicy",
+ "source": "packages/sandbox/sandbox/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/sandbox.zh.md",
+ "symbol": "SandboxEnforcement",
+ "source": "packages/sandbox/sandbox/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/sandbox.zh.md",
+ "symbol": "SandboxPolicy",
+ "source": "packages/sandbox/sandbox/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/sandbox.zh.md",
+ "symbol": "SandboxPolicyRequest",
+ "source": "packages/sandbox/sandbox-policy/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/sandbox.zh.md",
+ "symbol": "ConfinedArgv",
+ "source": "packages/sandbox/sandbox/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/code-runtime.zh.md",
+ "symbol": "CodeRunRequest",
+ "source": "packages/code-runtime/code-runtime/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/code-runtime.zh.md",
+ "symbol": "CodeRunResult",
+ "source": "packages/code-runtime/code-runtime/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/code-runtime.zh.md",
+ "symbol": "CodeBindingNamespace",
+ "source": "packages/code-runtime/code-runtime/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/code-runtime.zh.md",
+ "symbol": "CodeBindingFunction",
+ "source": "packages/code-runtime/code-runtime/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/code-runtime.zh.md",
+ "symbol": "CodeRunFailure",
+ "source": "packages/code-runtime/code-runtime/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/filesystem.zh.md",
+ "symbol": "FsTarget",
+ "source": "packages/fs/fs/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/filesystem.zh.md",
+ "symbol": "FsTargetKey",
+ "source": "packages/fs/fs/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/filesystem.zh.md",
+ "symbol": "FsVersion",
+ "source": "packages/fs/fs/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/filesystem.zh.md",
+ "symbol": "FsInfo",
+ "source": "packages/fs/fs/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/filesystem.zh.md",
+ "symbol": "FsPathInfo",
+ "source": "packages/fs/fs/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/filesystem.zh.md",
+ "symbol": "FsDirEntry",
+ "source": "packages/fs/fs/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/filesystem.zh.md",
+ "symbol": "FsWriteIntent",
+ "source": "packages/fs/fs/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/filesystem.zh.md",
+ "symbol": "FsWriteOutcome",
+ "source": "packages/fs/fs/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/filesystem.zh.md",
+ "symbol": "FsEditRequest",
+ "source": "packages/fs/fs/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/filesystem.zh.md",
+ "symbol": "FsEditOutcome",
+ "source": "packages/fs/fs/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/filesystem.zh.md",
+ "symbol": "FsErrorCode",
+ "source": "packages/fs/fs/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/filesystem.zh.md",
+ "symbol": "FsPolicyExec",
+ "source": "packages/fs/fs-policy/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/filesystem.zh.md",
+ "symbol": "FileReadOutcome",
+ "source": "packages/fs/tool-fs/src/read-render.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/skills.zh.md",
+ "symbol": "SkillSource",
+ "source": "packages/skill/skill/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/skills.zh.md",
+ "symbol": "SkillResourceBase",
+ "source": "packages/skill/skill/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/skills.zh.md",
+ "symbol": "SkillSummary",
+ "source": "packages/skill/skill/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/skills.zh.md",
+ "symbol": "SkillCandidate",
+ "source": "packages/skill/skill/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/skills.zh.md",
+ "symbol": "SkillDefinition",
+ "source": "packages/skill/skill/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/skills.zh.md",
+ "symbol": "SkillRegistration",
+ "source": "packages/skill/skill/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/skills.zh.md",
+ "symbol": "SkillLookupOptions",
+ "source": "packages/skill/skill/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/skills.zh.md",
+ "symbol": "SkillProvider",
+ "source": "packages/skill/skill/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/skills.zh.md",
+ "symbol": "Config",
+ "source": "packages/skill/skill/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/compaction.zh.md",
+ "symbol": "CompactionResult",
+ "source": "packages/compact/compact/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/compaction.zh.md",
+ "symbol": "CompactionTrigger",
+ "source": "packages/compact/compact/src/index.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/compaction.zh.md",
+ "symbol": "PrunedEntry",
+ "source": "packages/compact/compact-tool-result-prune/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/compaction.zh.md",
+ "symbol": "PruneResult",
+ "source": "packages/compact/compact-tool-result-prune/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/subagent.zh.md",
+ "symbol": "SubagentCapabilities",
+ "source": "packages/subagent/subagent/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/subagent.zh.md",
+ "symbol": "SubagentStartRequest",
+ "source": "packages/subagent/subagent/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/subagent.zh.md",
+ "symbol": "SubagentResult",
+ "source": "packages/subagent/subagent/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/subagent.zh.md",
+ "symbol": "SubagentStopReasonMap",
+ "source": "packages/subagent/subagent/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/subagent.zh.md",
+ "symbol": "SubagentRun",
+ "source": "packages/subagent/subagent/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/subagent.zh.md",
+ "symbol": "SubagentProvider",
+ "source": "packages/subagent/subagent/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/web.zh.md",
+ "symbol": "WebSearchRequest",
+ "source": "packages/web/web/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/web.zh.md",
+ "symbol": "WebSearchResult",
+ "source": "packages/web/web/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/web.zh.md",
+ "symbol": "WebSearchSource",
+ "source": "packages/web/web/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/web.zh.md",
+ "symbol": "WebFetchRequest",
+ "source": "packages/web/web/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/web.zh.md",
+ "symbol": "WebFetchResult",
+ "source": "packages/web/web/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/web.zh.md",
+ "symbol": "WebFetchBody",
+ "source": "packages/web/web/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/workflow.zh.md",
+ "symbol": "WorkflowStartRequest",
+ "source": "packages/workflow/workflow/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/workflow.zh.md",
+ "symbol": "WorkflowMeta",
+ "source": "packages/workflow/workflow/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/workflow.zh.md",
+ "symbol": "WorkflowResult",
+ "source": "packages/workflow/workflow/src/types.ts"
+ },
+ {
+ "doc": "docs/core-data-structures/workflow.zh.md",
+ "symbol": "WorkflowRun",
+ "source": "packages/workflow/workflow/src/types.ts"
}
]
}